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

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

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