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

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

https://bitbucket.org/ltratt/pypy
Python | 1264 lines | 1230 code | 17 blank | 17 comment | 3 complexity | f2fb91e482dc4113aeab2e34758d6163 MD5 | raw file
Possible License(s): Apache-2.0, AGPL-3.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file