PageRenderTime 53ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/pypy/lib-python/2.7/test/test_re.py

https://bitbucket.org/csenger/benchmarks
Python | 843 lines | 804 code | 21 blank | 18 comment | 4 complexity | 0d25261e7279743dbc7b5dce9e9e80ef MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, GPL-2.0
  1. from test.test_support import verbose, run_unittest, import_module
  2. import re
  3. from re import Scanner
  4. import sys, traceback
  5. from weakref import proxy
  6. # Misc tests from Tim Peters' re.doc
  7. # WARNING: Don't change details in these tests if you don't know
  8. # what you're doing. Some of these tests were carefuly modeled to
  9. # cover most of the code.
  10. import unittest
  11. class ReTests(unittest.TestCase):
  12. def test_weakref(self):
  13. s = 'QabbbcR'
  14. x = re.compile('ab+c')
  15. y = proxy(x)
  16. self.assertEqual(x.findall('QabbbcR'), y.findall('QabbbcR'))
  17. def test_search_star_plus(self):
  18. self.assertEqual(re.search('x*', 'axx').span(0), (0, 0))
  19. self.assertEqual(re.search('x*', 'axx').span(), (0, 0))
  20. self.assertEqual(re.search('x+', 'axx').span(0), (1, 3))
  21. self.assertEqual(re.search('x+', 'axx').span(), (1, 3))
  22. self.assertEqual(re.search('x', 'aaa'), None)
  23. self.assertEqual(re.match('a*', 'xxx').span(0), (0, 0))
  24. self.assertEqual(re.match('a*', 'xxx').span(), (0, 0))
  25. self.assertEqual(re.match('x*', 'xxxa').span(0), (0, 3))
  26. self.assertEqual(re.match('x*', 'xxxa').span(), (0, 3))
  27. self.assertEqual(re.match('a+', 'xxx'), None)
  28. def bump_num(self, matchobj):
  29. int_value = int(matchobj.group(0))
  30. return str(int_value + 1)
  31. def test_basic_re_sub(self):
  32. self.assertEqual(re.sub("(?i)b+", "x", "bbbb BBBB"), 'x x')
  33. self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y'),
  34. '9.3 -3 24x100y')
  35. self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', 3),
  36. '9.3 -3 23x99y')
  37. self.assertEqual(re.sub('.', lambda m: r"\n", 'x'), '\\n')
  38. self.assertEqual(re.sub('.', r"\n", 'x'), '\n')
  39. s = r"\1\1"
  40. self.assertEqual(re.sub('(.)', s, 'x'), 'xx')
  41. self.assertEqual(re.sub('(.)', re.escape(s), 'x'), s)
  42. self.assertEqual(re.sub('(.)', lambda m: s, 'x'), s)
  43. self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<a>', 'xx'), 'xxxx')
  44. self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<1>', 'xx'), 'xxxx')
  45. self.assertEqual(re.sub('(?P<unk>x)', '\g<unk>\g<unk>', 'xx'), 'xxxx')
  46. self.assertEqual(re.sub('(?P<unk>x)', '\g<1>\g<1>', 'xx'), 'xxxx')
  47. self.assertEqual(re.sub('a',r'\t\n\v\r\f\a\b\B\Z\a\A\w\W\s\S\d\D','a'),
  48. '\t\n\v\r\f\a\b\\B\\Z\a\\A\\w\\W\\s\\S\\d\\D')
  49. self.assertEqual(re.sub('a', '\t\n\v\r\f\a', 'a'), '\t\n\v\r\f\a')
  50. self.assertEqual(re.sub('a', '\t\n\v\r\f\a', 'a'),
  51. (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7)))
  52. self.assertEqual(re.sub('^\s*', 'X', 'test'), 'Xtest')
  53. def test_bug_449964(self):
  54. # fails for group followed by other escape
  55. self.assertEqual(re.sub(r'(?P<unk>x)', '\g<1>\g<1>\\b', 'xx'),
  56. 'xx\bxx\b')
  57. def test_bug_449000(self):
  58. # Test for sub() on escaped characters
  59. self.assertEqual(re.sub(r'\r\n', r'\n', 'abc\r\ndef\r\n'),
  60. 'abc\ndef\n')
  61. self.assertEqual(re.sub('\r\n', r'\n', 'abc\r\ndef\r\n'),
  62. 'abc\ndef\n')
  63. self.assertEqual(re.sub(r'\r\n', '\n', 'abc\r\ndef\r\n'),
  64. 'abc\ndef\n')
  65. self.assertEqual(re.sub('\r\n', '\n', 'abc\r\ndef\r\n'),
  66. 'abc\ndef\n')
  67. def test_bug_1140(self):
  68. # re.sub(x, y, u'') should return u'', not '', and
  69. # re.sub(x, y, '') should return '', not u''.
  70. # Also:
  71. # re.sub(x, y, unicode(x)) should return unicode(y), and
  72. # re.sub(x, y, str(x)) should return
  73. # str(y) if isinstance(y, str) else unicode(y).
  74. for x in 'x', u'x':
  75. for y in 'y', u'y':
  76. z = re.sub(x, y, u'')
  77. self.assertEqual(z, u'')
  78. self.assertEqual(type(z), unicode)
  79. #
  80. z = re.sub(x, y, '')
  81. self.assertEqual(z, '')
  82. self.assertEqual(type(z), str)
  83. #
  84. z = re.sub(x, y, unicode(x))
  85. self.assertEqual(z, y)
  86. self.assertEqual(type(z), unicode)
  87. #
  88. z = re.sub(x, y, str(x))
  89. self.assertEqual(z, y)
  90. self.assertEqual(type(z), type(y))
  91. def test_bug_1661(self):
  92. # Verify that flags do not get silently ignored with compiled patterns
  93. pattern = re.compile('.')
  94. self.assertRaises(ValueError, re.match, pattern, 'A', re.I)
  95. self.assertRaises(ValueError, re.search, pattern, 'A', re.I)
  96. self.assertRaises(ValueError, re.findall, pattern, 'A', re.I)
  97. self.assertRaises(ValueError, re.compile, pattern, re.I)
  98. def test_bug_3629(self):
  99. # A regex that triggered a bug in the sre-code validator
  100. re.compile("(?P<quote>)(?(quote))")
  101. def test_sub_template_numeric_escape(self):
  102. # bug 776311 and friends
  103. self.assertEqual(re.sub('x', r'\0', 'x'), '\0')
  104. self.assertEqual(re.sub('x', r'\000', 'x'), '\000')
  105. self.assertEqual(re.sub('x', r'\001', 'x'), '\001')
  106. self.assertEqual(re.sub('x', r'\008', 'x'), '\0' + '8')
  107. self.assertEqual(re.sub('x', r'\009', 'x'), '\0' + '9')
  108. self.assertEqual(re.sub('x', r'\111', 'x'), '\111')
  109. self.assertEqual(re.sub('x', r'\117', 'x'), '\117')
  110. self.assertEqual(re.sub('x', r'\1111', 'x'), '\1111')
  111. self.assertEqual(re.sub('x', r'\1111', 'x'), '\111' + '1')
  112. self.assertEqual(re.sub('x', r'\00', 'x'), '\x00')
  113. self.assertEqual(re.sub('x', r'\07', 'x'), '\x07')
  114. self.assertEqual(re.sub('x', r'\08', 'x'), '\0' + '8')
  115. self.assertEqual(re.sub('x', r'\09', 'x'), '\0' + '9')
  116. self.assertEqual(re.sub('x', r'\0a', 'x'), '\0' + 'a')
  117. self.assertEqual(re.sub('x', r'\400', 'x'), '\0')
  118. self.assertEqual(re.sub('x', r'\777', 'x'), '\377')
  119. self.assertRaises(re.error, re.sub, 'x', r'\1', 'x')
  120. self.assertRaises(re.error, re.sub, 'x', r'\8', 'x')
  121. self.assertRaises(re.error, re.sub, 'x', r'\9', 'x')
  122. self.assertRaises(re.error, re.sub, 'x', r'\11', 'x')
  123. self.assertRaises(re.error, re.sub, 'x', r'\18', 'x')
  124. self.assertRaises(re.error, re.sub, 'x', r'\1a', 'x')
  125. self.assertRaises(re.error, re.sub, 'x', r'\90', 'x')
  126. self.assertRaises(re.error, re.sub, 'x', r'\99', 'x')
  127. self.assertRaises(re.error, re.sub, 'x', r'\118', 'x') # r'\11' + '8'
  128. self.assertRaises(re.error, re.sub, 'x', r'\11a', 'x')
  129. self.assertRaises(re.error, re.sub, 'x', r'\181', 'x') # r'\18' + '1'
  130. self.assertRaises(re.error, re.sub, 'x', r'\800', 'x') # r'\80' + '0'
  131. # in python2.3 (etc), these loop endlessly in sre_parser.py
  132. self.assertEqual(re.sub('(((((((((((x)))))))))))', r'\11', 'x'), 'x')
  133. self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\118', 'xyz'),
  134. 'xz8')
  135. self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\11a', 'xyz'),
  136. 'xza')
  137. def test_qualified_re_sub(self):
  138. self.assertEqual(re.sub('a', 'b', 'aaaaa'), 'bbbbb')
  139. self.assertEqual(re.sub('a', 'b', 'aaaaa', 1), 'baaaa')
  140. def test_bug_114660(self):
  141. self.assertEqual(re.sub(r'(\S)\s+(\S)', r'\1 \2', 'hello there'),
  142. 'hello there')
  143. def test_bug_462270(self):
  144. # Test for empty sub() behaviour, see SF bug #462270
  145. self.assertEqual(re.sub('x*', '-', 'abxd'), '-a-b-d-')
  146. self.assertEqual(re.sub('x+', '-', 'abxd'), 'ab-d')
  147. def test_symbolic_refs(self):
  148. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a', 'xx')
  149. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<', 'xx')
  150. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g', 'xx')
  151. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a a>', 'xx')
  152. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<1a1>', 'xx')
  153. self.assertRaises(IndexError, re.sub, '(?P<a>x)', '\g<ab>', 'xx')
  154. self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\g<b>', 'xx')
  155. self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\\2', 'xx')
  156. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<-1>', 'xx')
  157. def test_re_subn(self):
  158. self.assertEqual(re.subn("(?i)b+", "x", "bbbb BBBB"), ('x x', 2))
  159. self.assertEqual(re.subn("b+", "x", "bbbb BBBB"), ('x BBBB', 1))
  160. self.assertEqual(re.subn("b+", "x", "xyz"), ('xyz', 0))
  161. self.assertEqual(re.subn("b*", "x", "xyz"), ('xxxyxzx', 4))
  162. self.assertEqual(re.subn("b*", "x", "xyz", 2), ('xxxyz', 2))
  163. def test_re_split(self):
  164. self.assertEqual(re.split(":", ":a:b::c"), ['', 'a', 'b', '', 'c'])
  165. self.assertEqual(re.split(":*", ":a:b::c"), ['', 'a', 'b', 'c'])
  166. self.assertEqual(re.split("(:*)", ":a:b::c"),
  167. ['', ':', 'a', ':', 'b', '::', 'c'])
  168. self.assertEqual(re.split("(?::*)", ":a:b::c"), ['', 'a', 'b', 'c'])
  169. self.assertEqual(re.split("(:)*", ":a:b::c"),
  170. ['', ':', 'a', ':', 'b', ':', 'c'])
  171. self.assertEqual(re.split("([b:]+)", ":a:b::c"),
  172. ['', ':', 'a', ':b::', 'c'])
  173. self.assertEqual(re.split("(b)|(:+)", ":a:b::c"),
  174. ['', None, ':', 'a', None, ':', '', 'b', None, '',
  175. None, '::', 'c'])
  176. self.assertEqual(re.split("(?:b)|(?::+)", ":a:b::c"),
  177. ['', 'a', '', '', 'c'])
  178. def test_qualified_re_split(self):
  179. self.assertEqual(re.split(":", ":a:b::c", 2), ['', 'a', 'b::c'])
  180. self.assertEqual(re.split(':', 'a:b:c:d', 2), ['a', 'b', 'c:d'])
  181. self.assertEqual(re.split("(:)", ":a:b::c", 2),
  182. ['', ':', 'a', ':', 'b::c'])
  183. self.assertEqual(re.split("(:*)", ":a:b::c", 2),
  184. ['', ':', 'a', ':', 'b::c'])
  185. def test_re_findall(self):
  186. self.assertEqual(re.findall(":+", "abc"), [])
  187. self.assertEqual(re.findall(":+", "a:b::c:::d"), [":", "::", ":::"])
  188. self.assertEqual(re.findall("(:+)", "a:b::c:::d"), [":", "::", ":::"])
  189. self.assertEqual(re.findall("(:)(:*)", "a:b::c:::d"), [(":", ""),
  190. (":", ":"),
  191. (":", "::")])
  192. def test_bug_117612(self):
  193. self.assertEqual(re.findall(r"(a|(b))", "aba"),
  194. [("a", ""),("b", "b"),("a", "")])
  195. def test_re_match(self):
  196. self.assertEqual(re.match('a', 'a').groups(), ())
  197. self.assertEqual(re.match('(a)', 'a').groups(), ('a',))
  198. self.assertEqual(re.match(r'(a)', 'a').group(0), 'a')
  199. self.assertEqual(re.match(r'(a)', 'a').group(1), 'a')
  200. self.assertEqual(re.match(r'(a)', 'a').group(1, 1), ('a', 'a'))
  201. pat = re.compile('((a)|(b))(c)?')
  202. self.assertEqual(pat.match('a').groups(), ('a', 'a', None, None))
  203. self.assertEqual(pat.match('b').groups(), ('b', None, 'b', None))
  204. self.assertEqual(pat.match('ac').groups(), ('a', 'a', None, 'c'))
  205. self.assertEqual(pat.match('bc').groups(), ('b', None, 'b', 'c'))
  206. self.assertEqual(pat.match('bc').groups(""), ('b', "", 'b', 'c'))
  207. # A single group
  208. m = re.match('(a)', 'a')
  209. self.assertEqual(m.group(0), 'a')
  210. self.assertEqual(m.group(0), 'a')
  211. self.assertEqual(m.group(1), 'a')
  212. self.assertEqual(m.group(1, 1), ('a', 'a'))
  213. pat = re.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
  214. self.assertEqual(pat.match('a').group(1, 2, 3), ('a', None, None))
  215. self.assertEqual(pat.match('b').group('a1', 'b2', 'c3'),
  216. (None, 'b', None))
  217. self.assertEqual(pat.match('ac').group(1, 'b2', 3), ('a', None, 'c'))
  218. def test_re_groupref_exists(self):
  219. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', '(a)').groups(),
  220. ('(', 'a'))
  221. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', 'a').groups(),
  222. (None, 'a'))
  223. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', 'a)'), None)
  224. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', '(a'), None)
  225. self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'ab').groups(),
  226. ('a', 'b'))
  227. self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'cd').groups(),
  228. (None, 'd'))
  229. self.assertEqual(re.match('^(?:(a)|c)((?(1)|d))$', 'cd').groups(),
  230. (None, 'd'))
  231. self.assertEqual(re.match('^(?:(a)|c)((?(1)|d))$', 'a').groups(),
  232. ('a', ''))
  233. # Tests for bug #1177831: exercise groups other than the first group
  234. p = re.compile('(?P<g1>a)(?P<g2>b)?((?(g2)c|d))')
  235. self.assertEqual(p.match('abc').groups(),
  236. ('a', 'b', 'c'))
  237. self.assertEqual(p.match('ad').groups(),
  238. ('a', None, 'd'))
  239. self.assertEqual(p.match('abd'), None)
  240. self.assertEqual(p.match('ac'), None)
  241. def test_re_groupref(self):
  242. self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a|').groups(),
  243. ('|', 'a'))
  244. self.assertEqual(re.match(r'^(\|)?([^()]+)\1?$', 'a').groups(),
  245. (None, 'a'))
  246. self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', 'a|'), None)
  247. self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a'), None)
  248. self.assertEqual(re.match(r'^(?:(a)|c)(\1)$', 'aa').groups(),
  249. ('a', 'a'))
  250. self.assertEqual(re.match(r'^(?:(a)|c)(\1)?$', 'c').groups(),
  251. (None, None))
  252. def test_groupdict(self):
  253. self.assertEqual(re.match('(?P<first>first) (?P<second>second)',
  254. 'first second').groupdict(),
  255. {'first':'first', 'second':'second'})
  256. def test_expand(self):
  257. self.assertEqual(re.match("(?P<first>first) (?P<second>second)",
  258. "first second")
  259. .expand(r"\2 \1 \g<second> \g<first>"),
  260. "second first second first")
  261. def test_repeat_minmax(self):
  262. self.assertEqual(re.match("^(\w){1}$", "abc"), None)
  263. self.assertEqual(re.match("^(\w){1}?$", "abc"), None)
  264. self.assertEqual(re.match("^(\w){1,2}$", "abc"), None)
  265. self.assertEqual(re.match("^(\w){1,2}?$", "abc"), None)
  266. self.assertEqual(re.match("^(\w){3}$", "abc").group(1), "c")
  267. self.assertEqual(re.match("^(\w){1,3}$", "abc").group(1), "c")
  268. self.assertEqual(re.match("^(\w){1,4}$", "abc").group(1), "c")
  269. self.assertEqual(re.match("^(\w){3,4}?$", "abc").group(1), "c")
  270. self.assertEqual(re.match("^(\w){3}?$", "abc").group(1), "c")
  271. self.assertEqual(re.match("^(\w){1,3}?$", "abc").group(1), "c")
  272. self.assertEqual(re.match("^(\w){1,4}?$", "abc").group(1), "c")
  273. self.assertEqual(re.match("^(\w){3,4}?$", "abc").group(1), "c")
  274. self.assertEqual(re.match("^x{1}$", "xxx"), None)
  275. self.assertEqual(re.match("^x{1}?$", "xxx"), None)
  276. self.assertEqual(re.match("^x{1,2}$", "xxx"), None)
  277. self.assertEqual(re.match("^x{1,2}?$", "xxx"), None)
  278. self.assertNotEqual(re.match("^x{3}$", "xxx"), None)
  279. self.assertNotEqual(re.match("^x{1,3}$", "xxx"), None)
  280. self.assertNotEqual(re.match("^x{1,4}$", "xxx"), None)
  281. self.assertNotEqual(re.match("^x{3,4}?$", "xxx"), None)
  282. self.assertNotEqual(re.match("^x{3}?$", "xxx"), None)
  283. self.assertNotEqual(re.match("^x{1,3}?$", "xxx"), None)
  284. self.assertNotEqual(re.match("^x{1,4}?$", "xxx"), None)
  285. self.assertNotEqual(re.match("^x{3,4}?$", "xxx"), None)
  286. self.assertEqual(re.match("^x{}$", "xxx"), None)
  287. self.assertNotEqual(re.match("^x{}$", "x{}"), None)
  288. def test_getattr(self):
  289. self.assertEqual(re.match("(a)", "a").pos, 0)
  290. self.assertEqual(re.match("(a)", "a").endpos, 1)
  291. self.assertEqual(re.match("(a)", "a").string, "a")
  292. self.assertEqual(re.match("(a)", "a").regs, ((0, 1), (0, 1)))
  293. self.assertNotEqual(re.match("(a)", "a").re, None)
  294. def test_special_escapes(self):
  295. self.assertEqual(re.search(r"\b(b.)\b",
  296. "abcd abc bcd bx").group(1), "bx")
  297. self.assertEqual(re.search(r"\B(b.)\B",
  298. "abc bcd bc abxd").group(1), "bx")
  299. self.assertEqual(re.search(r"\b(b.)\b",
  300. "abcd abc bcd bx", re.LOCALE).group(1), "bx")
  301. self.assertEqual(re.search(r"\B(b.)\B",
  302. "abc bcd bc abxd", re.LOCALE).group(1), "bx")
  303. self.assertEqual(re.search(r"\b(b.)\b",
  304. "abcd abc bcd bx", re.UNICODE).group(1), "bx")
  305. self.assertEqual(re.search(r"\B(b.)\B",
  306. "abc bcd bc abxd", re.UNICODE).group(1), "bx")
  307. self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc")
  308. self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc")
  309. self.assertEqual(re.search(r"^\Aabc\Z$", "\nabc\n", re.M), None)
  310. self.assertEqual(re.search(r"\b(b.)\b",
  311. u"abcd abc bcd bx").group(1), "bx")
  312. self.assertEqual(re.search(r"\B(b.)\B",
  313. u"abc bcd bc abxd").group(1), "bx")
  314. self.assertEqual(re.search(r"^abc$", u"\nabc\n", re.M).group(0), "abc")
  315. self.assertEqual(re.search(r"^\Aabc\Z$", u"abc", re.M).group(0), "abc")
  316. self.assertEqual(re.search(r"^\Aabc\Z$", u"\nabc\n", re.M), None)
  317. self.assertEqual(re.search(r"\d\D\w\W\s\S",
  318. "1aa! a").group(0), "1aa! a")
  319. self.assertEqual(re.search(r"\d\D\w\W\s\S",
  320. "1aa! a", re.LOCALE).group(0), "1aa! a")
  321. self.assertEqual(re.search(r"\d\D\w\W\s\S",
  322. "1aa! a", re.UNICODE).group(0), "1aa! a")
  323. def test_bigcharset(self):
  324. self.assertEqual(re.match(u"([\u2222\u2223])",
  325. u"\u2222").group(1), u"\u2222")
  326. self.assertEqual(re.match(u"([\u2222\u2223])",
  327. u"\u2222", re.UNICODE).group(1), u"\u2222")
  328. def test_anyall(self):
  329. self.assertEqual(re.match("a.b", "a\nb", re.DOTALL).group(0),
  330. "a\nb")
  331. self.assertEqual(re.match("a.*b", "a\n\nb", re.DOTALL).group(0),
  332. "a\n\nb")
  333. def test_non_consuming(self):
  334. self.assertEqual(re.match("(a(?=\s[^a]))", "a b").group(1), "a")
  335. self.assertEqual(re.match("(a(?=\s[^a]*))", "a b").group(1), "a")
  336. self.assertEqual(re.match("(a(?=\s[abc]))", "a b").group(1), "a")
  337. self.assertEqual(re.match("(a(?=\s[abc]*))", "a bc").group(1), "a")
  338. self.assertEqual(re.match(r"(a)(?=\s\1)", "a a").group(1), "a")
  339. self.assertEqual(re.match(r"(a)(?=\s\1*)", "a aa").group(1), "a")
  340. self.assertEqual(re.match(r"(a)(?=\s(abc|a))", "a a").group(1), "a")
  341. self.assertEqual(re.match(r"(a(?!\s[^a]))", "a a").group(1), "a")
  342. self.assertEqual(re.match(r"(a(?!\s[abc]))", "a d").group(1), "a")
  343. self.assertEqual(re.match(r"(a)(?!\s\1)", "a b").group(1), "a")
  344. self.assertEqual(re.match(r"(a)(?!\s(abc|a))", "a b").group(1), "a")
  345. def test_ignore_case(self):
  346. self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
  347. self.assertEqual(re.match("abc", u"ABC", re.I).group(0), "ABC")
  348. self.assertEqual(re.match(r"(a\s[^a])", "a b", re.I).group(1), "a b")
  349. self.assertEqual(re.match(r"(a\s[^a]*)", "a bb", re.I).group(1), "a bb")
  350. self.assertEqual(re.match(r"(a\s[abc])", "a b", re.I).group(1), "a b")
  351. self.assertEqual(re.match(r"(a\s[abc]*)", "a bb", re.I).group(1), "a bb")
  352. self.assertEqual(re.match(r"((a)\s\2)", "a a", re.I).group(1), "a a")
  353. self.assertEqual(re.match(r"((a)\s\2*)", "a aa", re.I).group(1), "a aa")
  354. self.assertEqual(re.match(r"((a)\s(abc|a))", "a a", re.I).group(1), "a a")
  355. self.assertEqual(re.match(r"((a)\s(abc|a)*)", "a aa", re.I).group(1), "a aa")
  356. def test_category(self):
  357. self.assertEqual(re.match(r"(\s)", " ").group(1), " ")
  358. def test_getlower(self):
  359. import _sre
  360. self.assertEqual(_sre.getlower(ord('A'), 0), ord('a'))
  361. self.assertEqual(_sre.getlower(ord('A'), re.LOCALE), ord('a'))
  362. self.assertEqual(_sre.getlower(ord('A'), re.UNICODE), ord('a'))
  363. self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
  364. self.assertEqual(re.match("abc", u"ABC", re.I).group(0), "ABC")
  365. def test_not_literal(self):
  366. self.assertEqual(re.search("\s([^a])", " b").group(1), "b")
  367. self.assertEqual(re.search("\s([^a]*)", " bb").group(1), "bb")
  368. def test_search_coverage(self):
  369. self.assertEqual(re.search("\s(b)", " b").group(1), "b")
  370. self.assertEqual(re.search("a\s", "a ").group(0), "a ")
  371. def test_re_escape(self):
  372. p=""
  373. for i in range(0, 256):
  374. p = p + chr(i)
  375. self.assertEqual(re.match(re.escape(chr(i)), chr(i)) is not None,
  376. True)
  377. self.assertEqual(re.match(re.escape(chr(i)), chr(i)).span(), (0,1))
  378. pat=re.compile(re.escape(p))
  379. self.assertEqual(pat.match(p) is not None, True)
  380. self.assertEqual(pat.match(p).span(), (0,256))
  381. def test_pickling(self):
  382. import pickle
  383. self.pickle_test(pickle)
  384. import cPickle
  385. self.pickle_test(cPickle)
  386. # old pickles expect the _compile() reconstructor in sre module
  387. import_module("sre", deprecated=True)
  388. from sre import _compile
  389. def pickle_test(self, pickle):
  390. oldpat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
  391. s = pickle.dumps(oldpat)
  392. newpat = pickle.loads(s)
  393. self.assertEqual(oldpat, newpat)
  394. def test_constants(self):
  395. self.assertEqual(re.I, re.IGNORECASE)
  396. self.assertEqual(re.L, re.LOCALE)
  397. self.assertEqual(re.M, re.MULTILINE)
  398. self.assertEqual(re.S, re.DOTALL)
  399. self.assertEqual(re.X, re.VERBOSE)
  400. def test_flags(self):
  401. for flag in [re.I, re.M, re.X, re.S, re.L]:
  402. self.assertNotEqual(re.compile('^pattern$', flag), None)
  403. def test_sre_character_literals(self):
  404. for i in [0, 8, 16, 32, 64, 127, 128, 255]:
  405. self.assertNotEqual(re.match(r"\%03o" % i, chr(i)), None)
  406. self.assertNotEqual(re.match(r"\%03o0" % i, chr(i)+"0"), None)
  407. self.assertNotEqual(re.match(r"\%03o8" % i, chr(i)+"8"), None)
  408. self.assertNotEqual(re.match(r"\x%02x" % i, chr(i)), None)
  409. self.assertNotEqual(re.match(r"\x%02x0" % i, chr(i)+"0"), None)
  410. self.assertNotEqual(re.match(r"\x%02xz" % i, chr(i)+"z"), None)
  411. self.assertRaises(re.error, re.match, "\911", "")
  412. def test_sre_character_class_literals(self):
  413. for i in [0, 8, 16, 32, 64, 127, 128, 255]:
  414. self.assertNotEqual(re.match(r"[\%03o]" % i, chr(i)), None)
  415. self.assertNotEqual(re.match(r"[\%03o0]" % i, chr(i)), None)
  416. self.assertNotEqual(re.match(r"[\%03o8]" % i, chr(i)), None)
  417. self.assertNotEqual(re.match(r"[\x%02x]" % i, chr(i)), None)
  418. self.assertNotEqual(re.match(r"[\x%02x0]" % i, chr(i)), None)
  419. self.assertNotEqual(re.match(r"[\x%02xz]" % i, chr(i)), None)
  420. self.assertRaises(re.error, re.match, "[\911]", "")
  421. def test_bug_113254(self):
  422. self.assertEqual(re.match(r'(a)|(b)', 'b').start(1), -1)
  423. self.assertEqual(re.match(r'(a)|(b)', 'b').end(1), -1)
  424. self.assertEqual(re.match(r'(a)|(b)', 'b').span(1), (-1, -1))
  425. def test_bug_527371(self):
  426. # bug described in patches 527371/672491
  427. self.assertEqual(re.match(r'(a)?a','a').lastindex, None)
  428. self.assertEqual(re.match(r'(a)(b)?b','ab').lastindex, 1)
  429. self.assertEqual(re.match(r'(?P<a>a)(?P<b>b)?b','ab').lastgroup, 'a')
  430. self.assertEqual(re.match("(?P<a>a(b))", "ab").lastgroup, 'a')
  431. self.assertEqual(re.match("((a))", "a").lastindex, 1)
  432. def test_bug_545855(self):
  433. # bug 545855 -- This pattern failed to cause a compile error as it
  434. # should, instead provoking a TypeError.
  435. self.assertRaises(re.error, re.compile, 'foo[a-')
  436. def test_bug_418626(self):
  437. # bugs 418626 at al. -- Testing Greg Chapman's addition of op code
  438. # SRE_OP_MIN_REPEAT_ONE for eliminating recursion on simple uses of
  439. # pattern '*?' on a long string.
  440. self.assertEqual(re.match('.*?c', 10000*'ab'+'cd').end(0), 20001)
  441. self.assertEqual(re.match('.*?cd', 5000*'ab'+'c'+5000*'ab'+'cde').end(0),
  442. 20003)
  443. self.assertEqual(re.match('.*?cd', 20000*'abc'+'de').end(0), 60001)
  444. # non-simple '*?' still used to hit the recursion limit, before the
  445. # non-recursive scheme was implemented.
  446. self.assertEqual(re.search('(a|b)*?c', 10000*'ab'+'cd').end(0), 20001)
  447. def test_bug_612074(self):
  448. pat=u"["+re.escape(u"\u2039")+u"]"
  449. self.assertEqual(re.compile(pat) and 1, 1)
  450. def test_stack_overflow(self):
  451. # nasty cases that used to overflow the straightforward recursive
  452. # implementation of repeated groups.
  453. self.assertEqual(re.match('(x)*', 50000*'x').group(1), 'x')
  454. self.assertEqual(re.match('(x)*y', 50000*'x'+'y').group(1), 'x')
  455. self.assertEqual(re.match('(x)*?y', 50000*'x'+'y').group(1), 'x')
  456. def test_scanner(self):
  457. def s_ident(scanner, token): return token
  458. def s_operator(scanner, token): return "op%s" % token
  459. def s_float(scanner, token): return float(token)
  460. def s_int(scanner, token): return int(token)
  461. scanner = Scanner([
  462. (r"[a-zA-Z_]\w*", s_ident),
  463. (r"\d+\.\d*", s_float),
  464. (r"\d+", s_int),
  465. (r"=|\+|-|\*|/", s_operator),
  466. (r"\s+", None),
  467. ])
  468. self.assertNotEqual(scanner.scanner.scanner("").pattern, None)
  469. self.assertEqual(scanner.scan("sum = 3*foo + 312.50 + bar"),
  470. (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5,
  471. 'op+', 'bar'], ''))
  472. def test_bug_448951(self):
  473. # bug 448951 (similar to 429357, but with single char match)
  474. # (Also test greedy matches.)
  475. for op in '','?','*':
  476. self.assertEqual(re.match(r'((.%s):)?z'%op, 'z').groups(),
  477. (None, None))
  478. self.assertEqual(re.match(r'((.%s):)?z'%op, 'a:z').groups(),
  479. ('a:', 'a'))
  480. def test_bug_725106(self):
  481. # capturing groups in alternatives in repeats
  482. self.assertEqual(re.match('^((a)|b)*', 'abc').groups(),
  483. ('b', 'a'))
  484. self.assertEqual(re.match('^(([ab])|c)*', 'abc').groups(),
  485. ('c', 'b'))
  486. self.assertEqual(re.match('^((d)|[ab])*', 'abc').groups(),
  487. ('b', None))
  488. self.assertEqual(re.match('^((a)c|[ab])*', 'abc').groups(),
  489. ('b', None))
  490. self.assertEqual(re.match('^((a)|b)*?c', 'abc').groups(),
  491. ('b', 'a'))
  492. self.assertEqual(re.match('^(([ab])|c)*?d', 'abcd').groups(),
  493. ('c', 'b'))
  494. self.assertEqual(re.match('^((d)|[ab])*?c', 'abc').groups(),
  495. ('b', None))
  496. self.assertEqual(re.match('^((a)c|[ab])*?c', 'abc').groups(),
  497. ('b', None))
  498. def test_bug_725149(self):
  499. # mark_stack_base restoring before restoring marks
  500. self.assertEqual(re.match('(a)(?:(?=(b)*)c)*', 'abb').groups(),
  501. ('a', None))
  502. self.assertEqual(re.match('(a)((?!(b)*))*', 'abb').groups(),
  503. ('a', None, None))
  504. def test_bug_764548(self):
  505. # bug 764548, re.compile() barfs on str/unicode subclasses
  506. try:
  507. unicode
  508. except NameError:
  509. return # no problem if we have no unicode
  510. class my_unicode(unicode): pass
  511. pat = re.compile(my_unicode("abc"))
  512. self.assertEqual(pat.match("xyz"), None)
  513. def test_finditer(self):
  514. iter = re.finditer(r":+", "a:b::c:::d")
  515. self.assertEqual([item.group(0) for item in iter],
  516. [":", "::", ":::"])
  517. def test_bug_926075(self):
  518. try:
  519. unicode
  520. except NameError:
  521. return # no problem if we have no unicode
  522. self.assertTrue(re.compile('bug_926075') is not
  523. re.compile(eval("u'bug_926075'")))
  524. def test_bug_931848(self):
  525. try:
  526. unicode
  527. except NameError:
  528. pass
  529. pattern = eval('u"[\u002E\u3002\uFF0E\uFF61]"')
  530. self.assertEqual(re.compile(pattern).split("a.b.c"),
  531. ['a','b','c'])
  532. def test_bug_581080(self):
  533. iter = re.finditer(r"\s", "a b")
  534. self.assertEqual(iter.next().span(), (1,2))
  535. self.assertRaises(StopIteration, iter.next)
  536. scanner = re.compile(r"\s").scanner("a b")
  537. self.assertEqual(scanner.search().span(), (1, 2))
  538. self.assertEqual(scanner.search(), None)
  539. def test_bug_817234(self):
  540. iter = re.finditer(r".*", "asdf")
  541. self.assertEqual(iter.next().span(), (0, 4))
  542. self.assertEqual(iter.next().span(), (4, 4))
  543. self.assertRaises(StopIteration, iter.next)
  544. def test_bug_6561(self):
  545. # '\d' should match characters in Unicode category 'Nd'
  546. # (Number, Decimal Digit), but not those in 'Nl' (Number,
  547. # Letter) or 'No' (Number, Other).
  548. decimal_digits = [
  549. u'\u0037', # '\N{DIGIT SEVEN}', category 'Nd'
  550. u'\u0e58', # '\N{THAI DIGIT SIX}', category 'Nd'
  551. u'\uff10', # '\N{FULLWIDTH DIGIT ZERO}', category 'Nd'
  552. ]
  553. for x in decimal_digits:
  554. self.assertEqual(re.match('^\d$', x, re.UNICODE).group(0), x)
  555. not_decimal_digits = [
  556. u'\u2165', # '\N{ROMAN NUMERAL SIX}', category 'Nl'
  557. u'\u3039', # '\N{HANGZHOU NUMERAL TWENTY}', category 'Nl'
  558. u'\u2082', # '\N{SUBSCRIPT TWO}', category 'No'
  559. u'\u32b4', # '\N{CIRCLED NUMBER THIRTY NINE}', category 'No'
  560. ]
  561. for x in not_decimal_digits:
  562. self.assertIsNone(re.match('^\d$', x, re.UNICODE))
  563. def test_empty_array(self):
  564. # SF buf 1647541
  565. import array
  566. for typecode in 'cbBuhHiIlLfd':
  567. a = array.array(typecode)
  568. self.assertEqual(re.compile("bla").match(a), None)
  569. self.assertEqual(re.compile("").match(a).groups(), ())
  570. def test_inline_flags(self):
  571. # Bug #1700
  572. upper_char = unichr(0x1ea0) # Latin Capital Letter A with Dot Bellow
  573. lower_char = unichr(0x1ea1) # Latin Small Letter A with Dot Bellow
  574. p = re.compile(upper_char, re.I | re.U)
  575. q = p.match(lower_char)
  576. self.assertNotEqual(q, None)
  577. p = re.compile(lower_char, re.I | re.U)
  578. q = p.match(upper_char)
  579. self.assertNotEqual(q, None)
  580. p = re.compile('(?i)' + upper_char, re.U)
  581. q = p.match(lower_char)
  582. self.assertNotEqual(q, None)
  583. p = re.compile('(?i)' + lower_char, re.U)
  584. q = p.match(upper_char)
  585. self.assertNotEqual(q, None)
  586. p = re.compile('(?iu)' + upper_char)
  587. q = p.match(lower_char)
  588. self.assertNotEqual(q, None)
  589. p = re.compile('(?iu)' + lower_char)
  590. q = p.match(upper_char)
  591. self.assertNotEqual(q, None)
  592. def test_dollar_matches_twice(self):
  593. "$ matches the end of string, and just before the terminating \n"
  594. pattern = re.compile('$')
  595. self.assertEqual(pattern.sub('#', 'a\nb\n'), 'a\nb#\n#')
  596. self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a\nb\nc#')
  597. self.assertEqual(pattern.sub('#', '\n'), '#\n#')
  598. pattern = re.compile('$', re.MULTILINE)
  599. self.assertEqual(pattern.sub('#', 'a\nb\n' ), 'a#\nb#\n#' )
  600. self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a#\nb#\nc#')
  601. self.assertEqual(pattern.sub('#', '\n'), '#\n#')
  602. def test_dealloc(self):
  603. # issue 3299: check for segfault in debug build
  604. import _sre
  605. # the overflow limit is different on wide and narrow builds and it
  606. # depends on the definition of SRE_CODE (see sre.h).
  607. # 2**128 should be big enough to overflow on both. For smaller values
  608. # a RuntimeError is raised instead of OverflowError.
  609. long_overflow = 2**128
  610. self.assertRaises(TypeError, re.finditer, "a", {})
  611. self.assertRaises(OverflowError, _sre.compile, "abc", 0, [long_overflow])
  612. def run_re_tests():
  613. from test.re_tests import tests, SUCCEED, FAIL, SYNTAX_ERROR
  614. if verbose:
  615. print 'Running re_tests test suite'
  616. else:
  617. # To save time, only run the first and last 10 tests
  618. #tests = tests[:10] + tests[-10:]
  619. pass
  620. for t in tests:
  621. sys.stdout.flush()
  622. pattern = s = outcome = repl = expected = None
  623. if len(t) == 5:
  624. pattern, s, outcome, repl, expected = t
  625. elif len(t) == 3:
  626. pattern, s, outcome = t
  627. else:
  628. raise ValueError, ('Test tuples should have 3 or 5 fields', t)
  629. try:
  630. obj = re.compile(pattern)
  631. except re.error:
  632. if outcome == SYNTAX_ERROR: pass # Expected a syntax error
  633. else:
  634. print '=== Syntax error:', t
  635. except KeyboardInterrupt: raise KeyboardInterrupt
  636. except:
  637. print '*** Unexpected error ***', t
  638. if verbose:
  639. traceback.print_exc(file=sys.stdout)
  640. else:
  641. try:
  642. result = obj.search(s)
  643. except re.error, msg:
  644. print '=== Unexpected exception', t, repr(msg)
  645. if outcome == SYNTAX_ERROR:
  646. # This should have been a syntax error; forget it.
  647. pass
  648. elif outcome == FAIL:
  649. if result is None: pass # No match, as expected
  650. else: print '=== Succeeded incorrectly', t
  651. elif outcome == SUCCEED:
  652. if result is not None:
  653. # Matched, as expected, so now we compute the
  654. # result string and compare it to our expected result.
  655. start, end = result.span(0)
  656. vardict={'found': result.group(0),
  657. 'groups': result.group(),
  658. 'flags': result.re.flags}
  659. for i in range(1, 100):
  660. try:
  661. gi = result.group(i)
  662. # Special hack because else the string concat fails:
  663. if gi is None:
  664. gi = "None"
  665. except IndexError:
  666. gi = "Error"
  667. vardict['g%d' % i] = gi
  668. for i in result.re.groupindex.keys():
  669. try:
  670. gi = result.group(i)
  671. if gi is None:
  672. gi = "None"
  673. except IndexError:
  674. gi = "Error"
  675. vardict[i] = gi
  676. repl = eval(repl, vardict)
  677. if repl != expected:
  678. print '=== grouping error', t,
  679. print repr(repl) + ' should be ' + repr(expected)
  680. else:
  681. print '=== Failed incorrectly', t
  682. # Try the match on a unicode string, and check that it
  683. # still succeeds.
  684. try:
  685. result = obj.search(unicode(s, "latin-1"))
  686. if result is None:
  687. print '=== Fails on unicode match', t
  688. except NameError:
  689. continue # 1.5.2
  690. except TypeError:
  691. continue # unicode test case
  692. # Try the match on a unicode pattern, and check that it
  693. # still succeeds.
  694. obj=re.compile(unicode(pattern, "latin-1"))
  695. result = obj.search(s)
  696. if result is None:
  697. print '=== Fails on unicode pattern match', t
  698. # Try the match with the search area limited to the extent
  699. # of the match and see if it still succeeds. \B will
  700. # break (because it won't match at the end or start of a
  701. # string), so we'll ignore patterns that feature it.
  702. if pattern[:2] != '\\B' and pattern[-2:] != '\\B' \
  703. and result is not None:
  704. obj = re.compile(pattern)
  705. result = obj.search(s, result.start(0), result.end(0) + 1)
  706. if result is None:
  707. print '=== Failed on range-limited match', t
  708. # Try the match with IGNORECASE enabled, and check that it
  709. # still succeeds.
  710. obj = re.compile(pattern, re.IGNORECASE)
  711. result = obj.search(s)
  712. if result is None:
  713. print '=== Fails on case-insensitive match', t
  714. # Try the match with LOCALE enabled, and check that it
  715. # still succeeds.
  716. obj = re.compile(pattern, re.LOCALE)
  717. result = obj.search(s)
  718. if result is None:
  719. print '=== Fails on locale-sensitive match', t
  720. # Try the match with UNICODE locale enabled, and check
  721. # that it still succeeds.
  722. obj = re.compile(pattern, re.UNICODE)
  723. result = obj.search(s)
  724. if result is None:
  725. print '=== Fails on unicode-sensitive match', t
  726. def test_main():
  727. run_unittest(ReTests)
  728. run_re_tests()
  729. if __name__ == "__main__":
  730. test_main()