PageRenderTime 60ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_re.py

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