PageRenderTime 59ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_re.py

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