PageRenderTime 57ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

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

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