»Core Development>Code coverage>Lib/test/test_re.py

Python code coverage for Lib/test/test_re.py

#countcontent
1n/afrom test.support import verbose, run_unittest, gc_collect, bigmemtest, _2G, \
2n/a cpython_only, captured_stdout
3n/aimport locale
4n/aimport re
5n/aimport sre_compile
6n/aimport string
7n/aimport unittest
8n/aimport warnings
9n/afrom re import Scanner
10n/afrom weakref import proxy
11n/a
12n/a# Misc tests from Tim Peters' re.doc
13n/a
14n/a# WARNING: Don't change details in these tests if you don't know
15n/a# what you're doing. Some of these tests were carefully modeled to
16n/a# cover most of the code.
17n/a
18n/aclass S(str):
19n/a def __getitem__(self, index):
20n/a return S(super().__getitem__(index))
21n/a
22n/aclass B(bytes):
23n/a def __getitem__(self, index):
24n/a return B(super().__getitem__(index))
25n/a
26n/aclass ReTests(unittest.TestCase):
27n/a
28n/a def assertTypedEqual(self, actual, expect, msg=None):
29n/a self.assertEqual(actual, expect, msg)
30n/a def recurse(actual, expect):
31n/a if isinstance(expect, (tuple, list)):
32n/a for x, y in zip(actual, expect):
33n/a recurse(x, y)
34n/a else:
35n/a self.assertIs(type(actual), type(expect), msg)
36n/a recurse(actual, expect)
37n/a
38n/a def checkPatternError(self, pattern, errmsg, pos=None):
39n/a with self.assertRaises(re.error) as cm:
40n/a re.compile(pattern)
41n/a with self.subTest(pattern=pattern):
42n/a err = cm.exception
43n/a self.assertEqual(err.msg, errmsg)
44n/a if pos is not None:
45n/a self.assertEqual(err.pos, pos)
46n/a
47n/a def checkTemplateError(self, pattern, repl, string, errmsg, pos=None):
48n/a with self.assertRaises(re.error) as cm:
49n/a re.sub(pattern, repl, string)
50n/a with self.subTest(pattern=pattern, repl=repl):
51n/a err = cm.exception
52n/a self.assertEqual(err.msg, errmsg)
53n/a if pos is not None:
54n/a self.assertEqual(err.pos, pos)
55n/a
56n/a def test_keep_buffer(self):
57n/a # See bug 14212
58n/a b = bytearray(b'x')
59n/a it = re.finditer(b'a', b)
60n/a with self.assertRaises(BufferError):
61n/a b.extend(b'x'*400)
62n/a list(it)
63n/a del it
64n/a gc_collect()
65n/a b.extend(b'x'*400)
66n/a
67n/a def test_weakref(self):
68n/a s = 'QabbbcR'
69n/a x = re.compile('ab+c')
70n/a y = proxy(x)
71n/a self.assertEqual(x.findall('QabbbcR'), y.findall('QabbbcR'))
72n/a
73n/a def test_search_star_plus(self):
74n/a self.assertEqual(re.search('x*', 'axx').span(0), (0, 0))
75n/a self.assertEqual(re.search('x*', 'axx').span(), (0, 0))
76n/a self.assertEqual(re.search('x+', 'axx').span(0), (1, 3))
77n/a self.assertEqual(re.search('x+', 'axx').span(), (1, 3))
78n/a self.assertIsNone(re.search('x', 'aaa'))
79n/a self.assertEqual(re.match('a*', 'xxx').span(0), (0, 0))
80n/a self.assertEqual(re.match('a*', 'xxx').span(), (0, 0))
81n/a self.assertEqual(re.match('x*', 'xxxa').span(0), (0, 3))
82n/a self.assertEqual(re.match('x*', 'xxxa').span(), (0, 3))
83n/a self.assertIsNone(re.match('a+', 'xxx'))
84n/a
85n/a def bump_num(self, matchobj):
86n/a int_value = int(matchobj.group(0))
87n/a return str(int_value + 1)
88n/a
89n/a def test_basic_re_sub(self):
90n/a self.assertTypedEqual(re.sub('y', 'a', 'xyz'), 'xaz')
91n/a self.assertTypedEqual(re.sub('y', S('a'), S('xyz')), 'xaz')
92n/a self.assertTypedEqual(re.sub(b'y', b'a', b'xyz'), b'xaz')
93n/a self.assertTypedEqual(re.sub(b'y', B(b'a'), B(b'xyz')), b'xaz')
94n/a self.assertTypedEqual(re.sub(b'y', bytearray(b'a'), bytearray(b'xyz')), b'xaz')
95n/a self.assertTypedEqual(re.sub(b'y', memoryview(b'a'), memoryview(b'xyz')), b'xaz')
96n/a for y in ("\xe0", "\u0430", "\U0001d49c"):
97n/a self.assertEqual(re.sub(y, 'a', 'x%sz' % y), 'xaz')
98n/a
99n/a self.assertEqual(re.sub("(?i)b+", "x", "bbbb BBBB"), 'x x')
100n/a self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y'),
101n/a '9.3 -3 24x100y')
102n/a self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', 3),
103n/a '9.3 -3 23x99y')
104n/a self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', count=3),
105n/a '9.3 -3 23x99y')
106n/a
107n/a self.assertEqual(re.sub('.', lambda m: r"\n", 'x'), '\\n')
108n/a self.assertEqual(re.sub('.', r"\n", 'x'), '\n')
109n/a
110n/a s = r"\1\1"
111n/a self.assertEqual(re.sub('(.)', s, 'x'), 'xx')
112n/a self.assertEqual(re.sub('(.)', re.escape(s), 'x'), s)
113n/a self.assertEqual(re.sub('(.)', lambda m: s, 'x'), s)
114n/a
115n/a self.assertEqual(re.sub('(?P<a>x)', r'\g<a>\g<a>', 'xx'), 'xxxx')
116n/a self.assertEqual(re.sub('(?P<a>x)', r'\g<a>\g<1>', 'xx'), 'xxxx')
117n/a self.assertEqual(re.sub('(?P<unk>x)', r'\g<unk>\g<unk>', 'xx'), 'xxxx')
118n/a self.assertEqual(re.sub('(?P<unk>x)', r'\g<1>\g<1>', 'xx'), 'xxxx')
119n/a
120n/a self.assertEqual(re.sub('a', r'\t\n\v\r\f\a\b', 'a'), '\t\n\v\r\f\a\b')
121n/a self.assertEqual(re.sub('a', '\t\n\v\r\f\a\b', 'a'), '\t\n\v\r\f\a\b')
122n/a self.assertEqual(re.sub('a', '\t\n\v\r\f\a\b', 'a'),
123n/a (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7)+chr(8)))
124n/a for c in 'cdehijklmopqsuwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
125n/a with self.subTest(c):
126n/a with self.assertRaises(re.error):
127n/a self.assertEqual(re.sub('a', '\\' + c, 'a'), '\\' + c)
128n/a
129n/a self.assertEqual(re.sub(r'^\s*', 'X', 'test'), 'Xtest')
130n/a
131n/a def test_bug_449964(self):
132n/a # fails for group followed by other escape
133n/a self.assertEqual(re.sub(r'(?P<unk>x)', r'\g<1>\g<1>\b', 'xx'),
134n/a 'xx\bxx\b')
135n/a
136n/a def test_bug_449000(self):
137n/a # Test for sub() on escaped characters
138n/a self.assertEqual(re.sub(r'\r\n', r'\n', 'abc\r\ndef\r\n'),
139n/a 'abc\ndef\n')
140n/a self.assertEqual(re.sub('\r\n', r'\n', 'abc\r\ndef\r\n'),
141n/a 'abc\ndef\n')
142n/a self.assertEqual(re.sub(r'\r\n', '\n', 'abc\r\ndef\r\n'),
143n/a 'abc\ndef\n')
144n/a self.assertEqual(re.sub('\r\n', '\n', 'abc\r\ndef\r\n'),
145n/a 'abc\ndef\n')
146n/a
147n/a def test_bug_1661(self):
148n/a # Verify that flags do not get silently ignored with compiled patterns
149n/a pattern = re.compile('.')
150n/a self.assertRaises(ValueError, re.match, pattern, 'A', re.I)
151n/a self.assertRaises(ValueError, re.search, pattern, 'A', re.I)
152n/a self.assertRaises(ValueError, re.findall, pattern, 'A', re.I)
153n/a self.assertRaises(ValueError, re.compile, pattern, re.I)
154n/a
155n/a def test_bug_3629(self):
156n/a # A regex that triggered a bug in the sre-code validator
157n/a re.compile("(?P<quote>)(?(quote))")
158n/a
159n/a def test_sub_template_numeric_escape(self):
160n/a # bug 776311 and friends
161n/a self.assertEqual(re.sub('x', r'\0', 'x'), '\0')
162n/a self.assertEqual(re.sub('x', r'\000', 'x'), '\000')
163n/a self.assertEqual(re.sub('x', r'\001', 'x'), '\001')
164n/a self.assertEqual(re.sub('x', r'\008', 'x'), '\0' + '8')
165n/a self.assertEqual(re.sub('x', r'\009', 'x'), '\0' + '9')
166n/a self.assertEqual(re.sub('x', r'\111', 'x'), '\111')
167n/a self.assertEqual(re.sub('x', r'\117', 'x'), '\117')
168n/a self.assertEqual(re.sub('x', r'\377', 'x'), '\377')
169n/a
170n/a self.assertEqual(re.sub('x', r'\1111', 'x'), '\1111')
171n/a self.assertEqual(re.sub('x', r'\1111', 'x'), '\111' + '1')
172n/a
173n/a self.assertEqual(re.sub('x', r'\00', 'x'), '\x00')
174n/a self.assertEqual(re.sub('x', r'\07', 'x'), '\x07')
175n/a self.assertEqual(re.sub('x', r'\08', 'x'), '\0' + '8')
176n/a self.assertEqual(re.sub('x', r'\09', 'x'), '\0' + '9')
177n/a self.assertEqual(re.sub('x', r'\0a', 'x'), '\0' + 'a')
178n/a
179n/a self.checkTemplateError('x', r'\400', 'x',
180n/a r'octal escape value \400 outside of '
181n/a r'range 0-0o377', 0)
182n/a self.checkTemplateError('x', r'\777', 'x',
183n/a r'octal escape value \777 outside of '
184n/a r'range 0-0o377', 0)
185n/a
186n/a self.checkTemplateError('x', r'\1', 'x', 'invalid group reference 1', 1)
187n/a self.checkTemplateError('x', r'\8', 'x', 'invalid group reference 8', 1)
188n/a self.checkTemplateError('x', r'\9', 'x', 'invalid group reference 9', 1)
189n/a self.checkTemplateError('x', r'\11', 'x', 'invalid group reference 11', 1)
190n/a self.checkTemplateError('x', r'\18', 'x', 'invalid group reference 18', 1)
191n/a self.checkTemplateError('x', r'\1a', 'x', 'invalid group reference 1', 1)
192n/a self.checkTemplateError('x', r'\90', 'x', 'invalid group reference 90', 1)
193n/a self.checkTemplateError('x', r'\99', 'x', 'invalid group reference 99', 1)
194n/a self.checkTemplateError('x', r'\118', 'x', 'invalid group reference 11', 1)
195n/a self.checkTemplateError('x', r'\11a', 'x', 'invalid group reference 11', 1)
196n/a self.checkTemplateError('x', r'\181', 'x', 'invalid group reference 18', 1)
197n/a self.checkTemplateError('x', r'\800', 'x', 'invalid group reference 80', 1)
198n/a self.checkTemplateError('x', r'\8', '', 'invalid group reference 8', 1)
199n/a
200n/a # in python2.3 (etc), these loop endlessly in sre_parser.py
201n/a self.assertEqual(re.sub('(((((((((((x)))))))))))', r'\11', 'x'), 'x')
202n/a self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\118', 'xyz'),
203n/a 'xz8')
204n/a self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\11a', 'xyz'),
205n/a 'xza')
206n/a
207n/a def test_qualified_re_sub(self):
208n/a self.assertEqual(re.sub('a', 'b', 'aaaaa'), 'bbbbb')
209n/a self.assertEqual(re.sub('a', 'b', 'aaaaa', 1), 'baaaa')
210n/a self.assertEqual(re.sub('a', 'b', 'aaaaa', count=1), 'baaaa')
211n/a
212n/a def test_bug_114660(self):
213n/a self.assertEqual(re.sub(r'(\S)\s+(\S)', r'\1 \2', 'hello there'),
214n/a 'hello there')
215n/a
216n/a def test_bug_462270(self):
217n/a # Test for empty sub() behaviour, see SF bug #462270
218n/a self.assertEqual(re.sub('x*', '-', 'abxd'), '-a-b-d-')
219n/a self.assertEqual(re.sub('x+', '-', 'abxd'), 'ab-d')
220n/a
221n/a def test_symbolic_groups(self):
222n/a re.compile(r'(?P<a>x)(?P=a)(?(a)y)')
223n/a re.compile(r'(?P<a1>x)(?P=a1)(?(a1)y)')
224n/a re.compile(r'(?P<a1>x)\1(?(1)y)')
225n/a self.checkPatternError(r'(?P<a>)(?P<a>)',
226n/a "redefinition of group name 'a' as group 2; "
227n/a "was group 1")
228n/a self.checkPatternError(r'(?P<a>(?P=a))',
229n/a "cannot refer to an open group", 10)
230n/a self.checkPatternError(r'(?Pxy)', 'unknown extension ?Px')
231n/a self.checkPatternError(r'(?P<a>)(?P=a', 'missing ), unterminated name', 11)
232n/a self.checkPatternError(r'(?P=', 'missing group name', 4)
233n/a self.checkPatternError(r'(?P=)', 'missing group name', 4)
234n/a self.checkPatternError(r'(?P=1)', "bad character in group name '1'", 4)
235n/a self.checkPatternError(r'(?P=a)', "unknown group name 'a'")
236n/a self.checkPatternError(r'(?P=a1)', "unknown group name 'a1'")
237n/a self.checkPatternError(r'(?P=a.)', "bad character in group name 'a.'", 4)
238n/a self.checkPatternError(r'(?P<)', 'missing >, unterminated name', 4)
239n/a self.checkPatternError(r'(?P<a', 'missing >, unterminated name', 4)
240n/a self.checkPatternError(r'(?P<', 'missing group name', 4)
241n/a self.checkPatternError(r'(?P<>)', 'missing group name', 4)
242n/a self.checkPatternError(r'(?P<1>)', "bad character in group name '1'", 4)
243n/a self.checkPatternError(r'(?P<a.>)', "bad character in group name 'a.'", 4)
244n/a self.checkPatternError(r'(?(', 'missing group name', 3)
245n/a self.checkPatternError(r'(?())', 'missing group name', 3)
246n/a self.checkPatternError(r'(?(a))', "unknown group name 'a'", 3)
247n/a self.checkPatternError(r'(?(-1))', "bad character in group name '-1'", 3)
248n/a self.checkPatternError(r'(?(1a))', "bad character in group name '1a'", 3)
249n/a self.checkPatternError(r'(?(a.))', "bad character in group name 'a.'", 3)
250n/a # New valid/invalid identifiers in Python 3
251n/a re.compile('(?P<µ>x)(?P=µ)(?(µ)y)')
252n/a re.compile('(?P<𝔘𝔫𝔦𝔠𝔬𝔡𝔢>x)(?P=𝔘𝔫𝔦𝔠𝔬𝔡𝔢)(?(𝔘𝔫𝔦𝔠𝔬𝔡𝔢)y)')
253n/a self.checkPatternError('(?P<©>x)', "bad character in group name '©'", 4)
254n/a # Support > 100 groups.
255n/a pat = '|'.join('x(?P<a%d>%x)y' % (i, i) for i in range(1, 200 + 1))
256n/a pat = '(?:%s)(?(200)z|t)' % pat
257n/a self.assertEqual(re.match(pat, 'xc8yz').span(), (0, 5))
258n/a
259n/a def test_symbolic_refs(self):
260n/a self.checkTemplateError('(?P<a>x)', r'\g<a', 'xx',
261n/a 'missing >, unterminated name', 3)
262n/a self.checkTemplateError('(?P<a>x)', r'\g<', 'xx',
263n/a 'missing group name', 3)
264n/a self.checkTemplateError('(?P<a>x)', r'\g', 'xx', 'missing <', 2)
265n/a self.checkTemplateError('(?P<a>x)', r'\g<a a>', 'xx',
266n/a "bad character in group name 'a a'", 3)
267n/a self.checkTemplateError('(?P<a>x)', r'\g<>', 'xx',
268n/a 'missing group name', 3)
269n/a self.checkTemplateError('(?P<a>x)', r'\g<1a1>', 'xx',
270n/a "bad character in group name '1a1'", 3)
271n/a self.checkTemplateError('(?P<a>x)', r'\g<2>', 'xx',
272n/a 'invalid group reference 2', 3)
273n/a self.checkTemplateError('(?P<a>x)', r'\2', 'xx',
274n/a 'invalid group reference 2', 1)
275n/a with self.assertRaisesRegex(IndexError, "unknown group name 'ab'"):
276n/a re.sub('(?P<a>x)', r'\g<ab>', 'xx')
277n/a self.assertEqual(re.sub('(?P<a>x)|(?P<b>y)', r'\g<b>', 'xx'), '')
278n/a self.assertEqual(re.sub('(?P<a>x)|(?P<b>y)', r'\2', 'xx'), '')
279n/a self.checkTemplateError('(?P<a>x)', r'\g<-1>', 'xx',
280n/a "bad character in group name '-1'", 3)
281n/a # New valid/invalid identifiers in Python 3
282n/a self.assertEqual(re.sub('(?P<µ>x)', r'\g<µ>', 'xx'), 'xx')
283n/a self.assertEqual(re.sub('(?P<𝔘𝔫𝔦𝔠𝔬𝔡𝔢>x)', r'\g<𝔘𝔫𝔦𝔠𝔬𝔡𝔢>', 'xx'), 'xx')
284n/a self.checkTemplateError('(?P<a>x)', r'\g<©>', 'xx',
285n/a "bad character in group name '©'", 3)
286n/a # Support > 100 groups.
287n/a pat = '|'.join('x(?P<a%d>%x)y' % (i, i) for i in range(1, 200 + 1))
288n/a self.assertEqual(re.sub(pat, r'\g<200>', 'xc8yzxc8y'), 'c8zc8')
289n/a
290n/a def test_re_subn(self):
291n/a self.assertEqual(re.subn("(?i)b+", "x", "bbbb BBBB"), ('x x', 2))
292n/a self.assertEqual(re.subn("b+", "x", "bbbb BBBB"), ('x BBBB', 1))
293n/a self.assertEqual(re.subn("b+", "x", "xyz"), ('xyz', 0))
294n/a self.assertEqual(re.subn("b*", "x", "xyz"), ('xxxyxzx', 4))
295n/a self.assertEqual(re.subn("b*", "x", "xyz", 2), ('xxxyz', 2))
296n/a self.assertEqual(re.subn("b*", "x", "xyz", count=2), ('xxxyz', 2))
297n/a
298n/a def test_re_split(self):
299n/a for string in ":a:b::c", S(":a:b::c"):
300n/a self.assertTypedEqual(re.split(":", string),
301n/a ['', 'a', 'b', '', 'c'])
302n/a self.assertTypedEqual(re.split(":+", string),
303n/a ['', 'a', 'b', 'c'])
304n/a self.assertTypedEqual(re.split("(:+)", string),
305n/a ['', ':', 'a', ':', 'b', '::', 'c'])
306n/a for string in (b":a:b::c", B(b":a:b::c"), bytearray(b":a:b::c"),
307n/a memoryview(b":a:b::c")):
308n/a self.assertTypedEqual(re.split(b":", string),
309n/a [b'', b'a', b'b', b'', b'c'])
310n/a self.assertTypedEqual(re.split(b":+", string),
311n/a [b'', b'a', b'b', b'c'])
312n/a self.assertTypedEqual(re.split(b"(:+)", string),
313n/a [b'', b':', b'a', b':', b'b', b'::', b'c'])
314n/a for a, b, c in ("\xe0\xdf\xe7", "\u0430\u0431\u0432",
315n/a "\U0001d49c\U0001d49e\U0001d4b5"):
316n/a string = ":%s:%s::%s" % (a, b, c)
317n/a self.assertEqual(re.split(":", string), ['', a, b, '', c])
318n/a self.assertEqual(re.split(":+", string), ['', a, b, c])
319n/a self.assertEqual(re.split("(:+)", string),
320n/a ['', ':', a, ':', b, '::', c])
321n/a
322n/a self.assertEqual(re.split("(?::+)", ":a:b::c"), ['', 'a', 'b', 'c'])
323n/a self.assertEqual(re.split("(:)+", ":a:b::c"),
324n/a ['', ':', 'a', ':', 'b', ':', 'c'])
325n/a self.assertEqual(re.split("([b:]+)", ":a:b::c"),
326n/a ['', ':', 'a', ':b::', 'c'])
327n/a self.assertEqual(re.split("(b)|(:+)", ":a:b::c"),
328n/a ['', None, ':', 'a', None, ':', '', 'b', None, '',
329n/a None, '::', 'c'])
330n/a self.assertEqual(re.split("(?:b)|(?::+)", ":a:b::c"),
331n/a ['', 'a', '', '', 'c'])
332n/a
333n/a for sep, expected in [
334n/a (':*', ['', 'a', 'b', 'c']),
335n/a ('(?::*)', ['', 'a', 'b', 'c']),
336n/a ('(:*)', ['', ':', 'a', ':', 'b', '::', 'c']),
337n/a ('(:)*', ['', ':', 'a', ':', 'b', ':', 'c']),
338n/a ]:
339n/a with self.subTest(sep=sep), self.assertWarns(FutureWarning):
340n/a self.assertTypedEqual(re.split(sep, ':a:b::c'), expected)
341n/a
342n/a for sep, expected in [
343n/a ('', [':a:b::c']),
344n/a (r'\b', [':a:b::c']),
345n/a (r'(?=:)', [':a:b::c']),
346n/a (r'(?<=:)', [':a:b::c']),
347n/a ]:
348n/a with self.subTest(sep=sep), self.assertRaises(ValueError):
349n/a self.assertTypedEqual(re.split(sep, ':a:b::c'), expected)
350n/a
351n/a def test_qualified_re_split(self):
352n/a self.assertEqual(re.split(":", ":a:b::c", 2), ['', 'a', 'b::c'])
353n/a self.assertEqual(re.split(":", ":a:b::c", maxsplit=2), ['', 'a', 'b::c'])
354n/a self.assertEqual(re.split(':', 'a:b:c:d', maxsplit=2), ['a', 'b', 'c:d'])
355n/a self.assertEqual(re.split("(:)", ":a:b::c", maxsplit=2),
356n/a ['', ':', 'a', ':', 'b::c'])
357n/a self.assertEqual(re.split("(:+)", ":a:b::c", maxsplit=2),
358n/a ['', ':', 'a', ':', 'b::c'])
359n/a with self.assertWarns(FutureWarning):
360n/a self.assertEqual(re.split("(:*)", ":a:b::c", maxsplit=2),
361n/a ['', ':', 'a', ':', 'b::c'])
362n/a
363n/a def test_re_findall(self):
364n/a self.assertEqual(re.findall(":+", "abc"), [])
365n/a for string in "a:b::c:::d", S("a:b::c:::d"):
366n/a self.assertTypedEqual(re.findall(":+", string),
367n/a [":", "::", ":::"])
368n/a self.assertTypedEqual(re.findall("(:+)", string),
369n/a [":", "::", ":::"])
370n/a self.assertTypedEqual(re.findall("(:)(:*)", string),
371n/a [(":", ""), (":", ":"), (":", "::")])
372n/a for string in (b"a:b::c:::d", B(b"a:b::c:::d"), bytearray(b"a:b::c:::d"),
373n/a memoryview(b"a:b::c:::d")):
374n/a self.assertTypedEqual(re.findall(b":+", string),
375n/a [b":", b"::", b":::"])
376n/a self.assertTypedEqual(re.findall(b"(:+)", string),
377n/a [b":", b"::", b":::"])
378n/a self.assertTypedEqual(re.findall(b"(:)(:*)", string),
379n/a [(b":", b""), (b":", b":"), (b":", b"::")])
380n/a for x in ("\xe0", "\u0430", "\U0001d49c"):
381n/a xx = x * 2
382n/a xxx = x * 3
383n/a string = "a%sb%sc%sd" % (x, xx, xxx)
384n/a self.assertEqual(re.findall("%s+" % x, string), [x, xx, xxx])
385n/a self.assertEqual(re.findall("(%s+)" % x, string), [x, xx, xxx])
386n/a self.assertEqual(re.findall("(%s)(%s*)" % (x, x), string),
387n/a [(x, ""), (x, x), (x, xx)])
388n/a
389n/a def test_bug_117612(self):
390n/a self.assertEqual(re.findall(r"(a|(b))", "aba"),
391n/a [("a", ""),("b", "b"),("a", "")])
392n/a
393n/a def test_re_match(self):
394n/a for string in 'a', S('a'):
395n/a self.assertEqual(re.match('a', string).groups(), ())
396n/a self.assertEqual(re.match('(a)', string).groups(), ('a',))
397n/a self.assertEqual(re.match('(a)', string).group(0), 'a')
398n/a self.assertEqual(re.match('(a)', string).group(1), 'a')
399n/a self.assertEqual(re.match('(a)', string).group(1, 1), ('a', 'a'))
400n/a for string in b'a', B(b'a'), bytearray(b'a'), memoryview(b'a'):
401n/a self.assertEqual(re.match(b'a', string).groups(), ())
402n/a self.assertEqual(re.match(b'(a)', string).groups(), (b'a',))
403n/a self.assertEqual(re.match(b'(a)', string).group(0), b'a')
404n/a self.assertEqual(re.match(b'(a)', string).group(1), b'a')
405n/a self.assertEqual(re.match(b'(a)', string).group(1, 1), (b'a', b'a'))
406n/a for a in ("\xe0", "\u0430", "\U0001d49c"):
407n/a self.assertEqual(re.match(a, a).groups(), ())
408n/a self.assertEqual(re.match('(%s)' % a, a).groups(), (a,))
409n/a self.assertEqual(re.match('(%s)' % a, a).group(0), a)
410n/a self.assertEqual(re.match('(%s)' % a, a).group(1), a)
411n/a self.assertEqual(re.match('(%s)' % a, a).group(1, 1), (a, a))
412n/a
413n/a pat = re.compile('((a)|(b))(c)?')
414n/a self.assertEqual(pat.match('a').groups(), ('a', 'a', None, None))
415n/a self.assertEqual(pat.match('b').groups(), ('b', None, 'b', None))
416n/a self.assertEqual(pat.match('ac').groups(), ('a', 'a', None, 'c'))
417n/a self.assertEqual(pat.match('bc').groups(), ('b', None, 'b', 'c'))
418n/a self.assertEqual(pat.match('bc').groups(""), ('b', "", 'b', 'c'))
419n/a
420n/a pat = re.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
421n/a self.assertEqual(pat.match('a').group(1, 2, 3), ('a', None, None))
422n/a self.assertEqual(pat.match('b').group('a1', 'b2', 'c3'),
423n/a (None, 'b', None))
424n/a self.assertEqual(pat.match('ac').group(1, 'b2', 3), ('a', None, 'c'))
425n/a
426n/a def test_group(self):
427n/a class Index:
428n/a def __init__(self, value):
429n/a self.value = value
430n/a def __index__(self):
431n/a return self.value
432n/a # A single group
433n/a m = re.match('(a)(b)', 'ab')
434n/a self.assertEqual(m.group(), 'ab')
435n/a self.assertEqual(m.group(0), 'ab')
436n/a self.assertEqual(m.group(1), 'a')
437n/a self.assertEqual(m.group(Index(1)), 'a')
438n/a self.assertRaises(IndexError, m.group, -1)
439n/a self.assertRaises(IndexError, m.group, 3)
440n/a self.assertRaises(IndexError, m.group, 1<<1000)
441n/a self.assertRaises(IndexError, m.group, Index(1<<1000))
442n/a self.assertRaises(IndexError, m.group, 'x')
443n/a # Multiple groups
444n/a self.assertEqual(m.group(2, 1), ('b', 'a'))
445n/a self.assertEqual(m.group(Index(2), Index(1)), ('b', 'a'))
446n/a
447n/a def test_match_getitem(self):
448n/a pat = re.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
449n/a
450n/a m = pat.match('a')
451n/a self.assertEqual(m['a1'], 'a')
452n/a self.assertEqual(m['b2'], None)
453n/a self.assertEqual(m['c3'], None)
454n/a self.assertEqual('a1={a1} b2={b2} c3={c3}'.format_map(m), 'a1=a b2=None c3=None')
455n/a self.assertEqual(m[0], 'a')
456n/a self.assertEqual(m[1], 'a')
457n/a self.assertEqual(m[2], None)
458n/a self.assertEqual(m[3], None)
459n/a with self.assertRaisesRegex(IndexError, 'no such group'):
460n/a m['X']
461n/a with self.assertRaisesRegex(IndexError, 'no such group'):
462n/a m[-1]
463n/a with self.assertRaisesRegex(IndexError, 'no such group'):
464n/a m[4]
465n/a with self.assertRaisesRegex(IndexError, 'no such group'):
466n/a m[0, 1]
467n/a with self.assertRaisesRegex(IndexError, 'no such group'):
468n/a m[(0,)]
469n/a with self.assertRaisesRegex(IndexError, 'no such group'):
470n/a m[(0, 1)]
471n/a with self.assertRaisesRegex(KeyError, 'a2'):
472n/a 'a1={a2}'.format_map(m)
473n/a
474n/a m = pat.match('ac')
475n/a self.assertEqual(m['a1'], 'a')
476n/a self.assertEqual(m['b2'], None)
477n/a self.assertEqual(m['c3'], 'c')
478n/a self.assertEqual('a1={a1} b2={b2} c3={c3}'.format_map(m), 'a1=a b2=None c3=c')
479n/a self.assertEqual(m[0], 'ac')
480n/a self.assertEqual(m[1], 'a')
481n/a self.assertEqual(m[2], None)
482n/a self.assertEqual(m[3], 'c')
483n/a
484n/a # Cannot assign.
485n/a with self.assertRaises(TypeError):
486n/a m[0] = 1
487n/a
488n/a # No len().
489n/a self.assertRaises(TypeError, len, m)
490n/a
491n/a def test_re_fullmatch(self):
492n/a # Issue 16203: Proposal: add re.fullmatch() method.
493n/a self.assertEqual(re.fullmatch(r"a", "a").span(), (0, 1))
494n/a for string in "ab", S("ab"):
495n/a self.assertEqual(re.fullmatch(r"a|ab", string).span(), (0, 2))
496n/a for string in b"ab", B(b"ab"), bytearray(b"ab"), memoryview(b"ab"):
497n/a self.assertEqual(re.fullmatch(br"a|ab", string).span(), (0, 2))
498n/a for a, b in "\xe0\xdf", "\u0430\u0431", "\U0001d49c\U0001d49e":
499n/a r = r"%s|%s" % (a, a + b)
500n/a self.assertEqual(re.fullmatch(r, a + b).span(), (0, 2))
501n/a self.assertEqual(re.fullmatch(r".*?$", "abc").span(), (0, 3))
502n/a self.assertEqual(re.fullmatch(r".*?", "abc").span(), (0, 3))
503n/a self.assertEqual(re.fullmatch(r"a.*?b", "ab").span(), (0, 2))
504n/a self.assertEqual(re.fullmatch(r"a.*?b", "abb").span(), (0, 3))
505n/a self.assertEqual(re.fullmatch(r"a.*?b", "axxb").span(), (0, 4))
506n/a self.assertIsNone(re.fullmatch(r"a+", "ab"))
507n/a self.assertIsNone(re.fullmatch(r"abc$", "abc\n"))
508n/a self.assertIsNone(re.fullmatch(r"abc\Z", "abc\n"))
509n/a self.assertIsNone(re.fullmatch(r"(?m)abc$", "abc\n"))
510n/a self.assertEqual(re.fullmatch(r"ab(?=c)cd", "abcd").span(), (0, 4))
511n/a self.assertEqual(re.fullmatch(r"ab(?<=b)cd", "abcd").span(), (0, 4))
512n/a self.assertEqual(re.fullmatch(r"(?=a|ab)ab", "ab").span(), (0, 2))
513n/a
514n/a self.assertEqual(
515n/a re.compile(r"bc").fullmatch("abcd", pos=1, endpos=3).span(), (1, 3))
516n/a self.assertEqual(
517n/a re.compile(r".*?$").fullmatch("abcd", pos=1, endpos=3).span(), (1, 3))
518n/a self.assertEqual(
519n/a re.compile(r".*?").fullmatch("abcd", pos=1, endpos=3).span(), (1, 3))
520n/a
521n/a def test_re_groupref_exists(self):
522n/a self.assertEqual(re.match(r'^(\()?([^()]+)(?(1)\))$', '(a)').groups(),
523n/a ('(', 'a'))
524n/a self.assertEqual(re.match(r'^(\()?([^()]+)(?(1)\))$', 'a').groups(),
525n/a (None, 'a'))
526n/a self.assertIsNone(re.match(r'^(\()?([^()]+)(?(1)\))$', 'a)'))
527n/a self.assertIsNone(re.match(r'^(\()?([^()]+)(?(1)\))$', '(a'))
528n/a self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'ab').groups(),
529n/a ('a', 'b'))
530n/a self.assertEqual(re.match(r'^(?:(a)|c)((?(1)b|d))$', 'cd').groups(),
531n/a (None, 'd'))
532n/a self.assertEqual(re.match(r'^(?:(a)|c)((?(1)|d))$', 'cd').groups(),
533n/a (None, 'd'))
534n/a self.assertEqual(re.match(r'^(?:(a)|c)((?(1)|d))$', 'a').groups(),
535n/a ('a', ''))
536n/a
537n/a # Tests for bug #1177831: exercise groups other than the first group
538n/a p = re.compile('(?P<g1>a)(?P<g2>b)?((?(g2)c|d))')
539n/a self.assertEqual(p.match('abc').groups(),
540n/a ('a', 'b', 'c'))
541n/a self.assertEqual(p.match('ad').groups(),
542n/a ('a', None, 'd'))
543n/a self.assertIsNone(p.match('abd'))
544n/a self.assertIsNone(p.match('ac'))
545n/a
546n/a # Support > 100 groups.
547n/a pat = '|'.join('x(?P<a%d>%x)y' % (i, i) for i in range(1, 200 + 1))
548n/a pat = '(?:%s)(?(200)z)' % pat
549n/a self.assertEqual(re.match(pat, 'xc8yz').span(), (0, 5))
550n/a
551n/a self.checkPatternError(r'(?P<a>)(?(0))', 'bad group number', 10)
552n/a self.checkPatternError(r'()(?(1)a|b',
553n/a 'missing ), unterminated subpattern', 2)
554n/a self.checkPatternError(r'()(?(1)a|b|c)',
555n/a 'conditional backref with more than '
556n/a 'two branches', 10)
557n/a
558n/a def test_re_groupref_overflow(self):
559n/a from sre_constants import MAXGROUPS
560n/a self.checkTemplateError('()', r'\g<%s>' % MAXGROUPS, 'xx',
561n/a 'invalid group reference %d' % MAXGROUPS, 3)
562n/a self.checkPatternError(r'(?P<a>)(?(%d))' % MAXGROUPS,
563n/a 'invalid group reference %d' % MAXGROUPS, 10)
564n/a
565n/a def test_re_groupref(self):
566n/a self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a|').groups(),
567n/a ('|', 'a'))
568n/a self.assertEqual(re.match(r'^(\|)?([^()]+)\1?$', 'a').groups(),
569n/a (None, 'a'))
570n/a self.assertIsNone(re.match(r'^(\|)?([^()]+)\1$', 'a|'))
571n/a self.assertIsNone(re.match(r'^(\|)?([^()]+)\1$', '|a'))
572n/a self.assertEqual(re.match(r'^(?:(a)|c)(\1)$', 'aa').groups(),
573n/a ('a', 'a'))
574n/a self.assertEqual(re.match(r'^(?:(a)|c)(\1)?$', 'c').groups(),
575n/a (None, None))
576n/a
577n/a self.checkPatternError(r'(abc\1)', 'cannot refer to an open group', 4)
578n/a
579n/a def test_groupdict(self):
580n/a self.assertEqual(re.match('(?P<first>first) (?P<second>second)',
581n/a 'first second').groupdict(),
582n/a {'first':'first', 'second':'second'})
583n/a
584n/a def test_expand(self):
585n/a self.assertEqual(re.match("(?P<first>first) (?P<second>second)",
586n/a "first second")
587n/a .expand(r"\2 \1 \g<second> \g<first>"),
588n/a "second first second first")
589n/a self.assertEqual(re.match("(?P<first>first)|(?P<second>second)",
590n/a "first")
591n/a .expand(r"\2 \g<second>"),
592n/a " ")
593n/a
594n/a def test_repeat_minmax(self):
595n/a self.assertIsNone(re.match(r"^(\w){1}$", "abc"))
596n/a self.assertIsNone(re.match(r"^(\w){1}?$", "abc"))
597n/a self.assertIsNone(re.match(r"^(\w){1,2}$", "abc"))
598n/a self.assertIsNone(re.match(r"^(\w){1,2}?$", "abc"))
599n/a
600n/a self.assertEqual(re.match(r"^(\w){3}$", "abc").group(1), "c")
601n/a self.assertEqual(re.match(r"^(\w){1,3}$", "abc").group(1), "c")
602n/a self.assertEqual(re.match(r"^(\w){1,4}$", "abc").group(1), "c")
603n/a self.assertEqual(re.match(r"^(\w){3,4}?$", "abc").group(1), "c")
604n/a self.assertEqual(re.match(r"^(\w){3}?$", "abc").group(1), "c")
605n/a self.assertEqual(re.match(r"^(\w){1,3}?$", "abc").group(1), "c")
606n/a self.assertEqual(re.match(r"^(\w){1,4}?$", "abc").group(1), "c")
607n/a self.assertEqual(re.match(r"^(\w){3,4}?$", "abc").group(1), "c")
608n/a
609n/a self.assertIsNone(re.match(r"^x{1}$", "xxx"))
610n/a self.assertIsNone(re.match(r"^x{1}?$", "xxx"))
611n/a self.assertIsNone(re.match(r"^x{1,2}$", "xxx"))
612n/a self.assertIsNone(re.match(r"^x{1,2}?$", "xxx"))
613n/a
614n/a self.assertTrue(re.match(r"^x{3}$", "xxx"))
615n/a self.assertTrue(re.match(r"^x{1,3}$", "xxx"))
616n/a self.assertTrue(re.match(r"^x{3,3}$", "xxx"))
617n/a self.assertTrue(re.match(r"^x{1,4}$", "xxx"))
618n/a self.assertTrue(re.match(r"^x{3,4}?$", "xxx"))
619n/a self.assertTrue(re.match(r"^x{3}?$", "xxx"))
620n/a self.assertTrue(re.match(r"^x{1,3}?$", "xxx"))
621n/a self.assertTrue(re.match(r"^x{1,4}?$", "xxx"))
622n/a self.assertTrue(re.match(r"^x{3,4}?$", "xxx"))
623n/a
624n/a self.assertIsNone(re.match(r"^x{}$", "xxx"))
625n/a self.assertTrue(re.match(r"^x{}$", "x{}"))
626n/a
627n/a self.checkPatternError(r'x{2,1}',
628n/a 'min repeat greater than max repeat', 2)
629n/a
630n/a def test_getattr(self):
631n/a self.assertEqual(re.compile("(?i)(a)(b)").pattern, "(?i)(a)(b)")
632n/a self.assertEqual(re.compile("(?i)(a)(b)").flags, re.I | re.U)
633n/a self.assertEqual(re.compile("(?i)(a)(b)").groups, 2)
634n/a self.assertEqual(re.compile("(?i)(a)(b)").groupindex, {})
635n/a self.assertEqual(re.compile("(?i)(?P<first>a)(?P<other>b)").groupindex,
636n/a {'first': 1, 'other': 2})
637n/a
638n/a self.assertEqual(re.match("(a)", "a").pos, 0)
639n/a self.assertEqual(re.match("(a)", "a").endpos, 1)
640n/a self.assertEqual(re.match("(a)", "a").string, "a")
641n/a self.assertEqual(re.match("(a)", "a").regs, ((0, 1), (0, 1)))
642n/a self.assertTrue(re.match("(a)", "a").re)
643n/a
644n/a # Issue 14260. groupindex should be non-modifiable mapping.
645n/a p = re.compile(r'(?i)(?P<first>a)(?P<other>b)')
646n/a self.assertEqual(sorted(p.groupindex), ['first', 'other'])
647n/a self.assertEqual(p.groupindex['other'], 2)
648n/a with self.assertRaises(TypeError):
649n/a p.groupindex['other'] = 0
650n/a self.assertEqual(p.groupindex['other'], 2)
651n/a
652n/a def test_special_escapes(self):
653n/a self.assertEqual(re.search(r"\b(b.)\b",
654n/a "abcd abc bcd bx").group(1), "bx")
655n/a self.assertEqual(re.search(r"\B(b.)\B",
656n/a "abc bcd bc abxd").group(1), "bx")
657n/a self.assertEqual(re.search(r"\b(b.)\b",
658n/a "abcd abc bcd bx", re.ASCII).group(1), "bx")
659n/a self.assertEqual(re.search(r"\B(b.)\B",
660n/a "abc bcd bc abxd", re.ASCII).group(1), "bx")
661n/a self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc")
662n/a self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc")
663n/a self.assertIsNone(re.search(r"^\Aabc\Z$", "\nabc\n", re.M))
664n/a self.assertEqual(re.search(br"\b(b.)\b",
665n/a b"abcd abc bcd bx").group(1), b"bx")
666n/a self.assertEqual(re.search(br"\B(b.)\B",
667n/a b"abc bcd bc abxd").group(1), b"bx")
668n/a self.assertEqual(re.search(br"\b(b.)\b",
669n/a b"abcd abc bcd bx", re.LOCALE).group(1), b"bx")
670n/a self.assertEqual(re.search(br"\B(b.)\B",
671n/a b"abc bcd bc abxd", re.LOCALE).group(1), b"bx")
672n/a self.assertEqual(re.search(br"^abc$", b"\nabc\n", re.M).group(0), b"abc")
673n/a self.assertEqual(re.search(br"^\Aabc\Z$", b"abc", re.M).group(0), b"abc")
674n/a self.assertIsNone(re.search(br"^\Aabc\Z$", b"\nabc\n", re.M))
675n/a self.assertEqual(re.search(r"\d\D\w\W\s\S",
676n/a "1aa! a").group(0), "1aa! a")
677n/a self.assertEqual(re.search(br"\d\D\w\W\s\S",
678n/a b"1aa! a").group(0), b"1aa! a")
679n/a self.assertEqual(re.search(r"\d\D\w\W\s\S",
680n/a "1aa! a", re.ASCII).group(0), "1aa! a")
681n/a self.assertEqual(re.search(br"\d\D\w\W\s\S",
682n/a b"1aa! a", re.LOCALE).group(0), b"1aa! a")
683n/a
684n/a def test_other_escapes(self):
685n/a self.checkPatternError("\\", 'bad escape (end of pattern)', 0)
686n/a self.assertEqual(re.match(r"\(", '(').group(), '(')
687n/a self.assertIsNone(re.match(r"\(", ')'))
688n/a self.assertEqual(re.match(r"\\", '\\').group(), '\\')
689n/a self.assertEqual(re.match(r"[\]]", ']').group(), ']')
690n/a self.assertIsNone(re.match(r"[\]]", '['))
691n/a self.assertEqual(re.match(r"[a\-c]", '-').group(), '-')
692n/a self.assertIsNone(re.match(r"[a\-c]", 'b'))
693n/a self.assertEqual(re.match(r"[\^a]+", 'a^').group(), 'a^')
694n/a self.assertIsNone(re.match(r"[\^a]+", 'b'))
695n/a re.purge() # for warnings
696n/a for c in 'ceghijklmopqyzCEFGHIJKLMNOPQRTVXY':
697n/a with self.subTest(c):
698n/a self.assertRaises(re.error, re.compile, '\\%c' % c)
699n/a for c in 'ceghijklmopqyzABCEFGHIJKLMNOPQRTVXYZ':
700n/a with self.subTest(c):
701n/a self.assertRaises(re.error, re.compile, '[\\%c]' % c)
702n/a
703n/a def test_string_boundaries(self):
704n/a # See http://bugs.python.org/issue10713
705n/a self.assertEqual(re.search(r"\b(abc)\b", "abc").group(1),
706n/a "abc")
707n/a # There's a word boundary at the start of a string.
708n/a self.assertTrue(re.match(r"\b", "abc"))
709n/a # A non-empty string includes a non-boundary zero-length match.
710n/a self.assertTrue(re.search(r"\B", "abc"))
711n/a # There is no non-boundary match at the start of a string.
712n/a self.assertFalse(re.match(r"\B", "abc"))
713n/a # However, an empty string contains no word boundaries, and also no
714n/a # non-boundaries.
715n/a self.assertIsNone(re.search(r"\B", ""))
716n/a # This one is questionable and different from the perlre behaviour,
717n/a # but describes current behavior.
718n/a self.assertIsNone(re.search(r"\b", ""))
719n/a # A single word-character string has two boundaries, but no
720n/a # non-boundary gaps.
721n/a self.assertEqual(len(re.findall(r"\b", "a")), 2)
722n/a self.assertEqual(len(re.findall(r"\B", "a")), 0)
723n/a # If there are no words, there are no boundaries
724n/a self.assertEqual(len(re.findall(r"\b", " ")), 0)
725n/a self.assertEqual(len(re.findall(r"\b", " ")), 0)
726n/a # Can match around the whitespace.
727n/a self.assertEqual(len(re.findall(r"\B", " ")), 2)
728n/a
729n/a def test_bigcharset(self):
730n/a self.assertEqual(re.match("([\u2222\u2223])",
731n/a "\u2222").group(1), "\u2222")
732n/a r = '[%s]' % ''.join(map(chr, range(256, 2**16, 255)))
733n/a self.assertEqual(re.match(r, "\uff01").group(), "\uff01")
734n/a
735n/a def test_big_codesize(self):
736n/a # Issue #1160
737n/a r = re.compile('|'.join(('%d'%x for x in range(10000))))
738n/a self.assertTrue(r.match('1000'))
739n/a self.assertTrue(r.match('9999'))
740n/a
741n/a def test_anyall(self):
742n/a self.assertEqual(re.match("a.b", "a\nb", re.DOTALL).group(0),
743n/a "a\nb")
744n/a self.assertEqual(re.match("a.*b", "a\n\nb", re.DOTALL).group(0),
745n/a "a\n\nb")
746n/a
747n/a def test_lookahead(self):
748n/a self.assertEqual(re.match(r"(a(?=\s[^a]))", "a b").group(1), "a")
749n/a self.assertEqual(re.match(r"(a(?=\s[^a]*))", "a b").group(1), "a")
750n/a self.assertEqual(re.match(r"(a(?=\s[abc]))", "a b").group(1), "a")
751n/a self.assertEqual(re.match(r"(a(?=\s[abc]*))", "a bc").group(1), "a")
752n/a self.assertEqual(re.match(r"(a)(?=\s\1)", "a a").group(1), "a")
753n/a self.assertEqual(re.match(r"(a)(?=\s\1*)", "a aa").group(1), "a")
754n/a self.assertEqual(re.match(r"(a)(?=\s(abc|a))", "a a").group(1), "a")
755n/a
756n/a self.assertEqual(re.match(r"(a(?!\s[^a]))", "a a").group(1), "a")
757n/a self.assertEqual(re.match(r"(a(?!\s[abc]))", "a d").group(1), "a")
758n/a self.assertEqual(re.match(r"(a)(?!\s\1)", "a b").group(1), "a")
759n/a self.assertEqual(re.match(r"(a)(?!\s(abc|a))", "a b").group(1), "a")
760n/a
761n/a # Group reference.
762n/a self.assertTrue(re.match(r'(a)b(?=\1)a', 'aba'))
763n/a self.assertIsNone(re.match(r'(a)b(?=\1)c', 'abac'))
764n/a # Conditional group reference.
765n/a self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(2)x|c))c', 'abc'))
766n/a self.assertIsNone(re.match(r'(?:(a)|(x))b(?=(?(2)c|x))c', 'abc'))
767n/a self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(2)x|c))c', 'abc'))
768n/a self.assertIsNone(re.match(r'(?:(a)|(x))b(?=(?(1)b|x))c', 'abc'))
769n/a self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(1)c|x))c', 'abc'))
770n/a # Group used before defined.
771n/a self.assertTrue(re.match(r'(a)b(?=(?(2)x|c))(c)', 'abc'))
772n/a self.assertIsNone(re.match(r'(a)b(?=(?(2)b|x))(c)', 'abc'))
773n/a self.assertTrue(re.match(r'(a)b(?=(?(1)c|x))(c)', 'abc'))
774n/a
775n/a def test_lookbehind(self):
776n/a self.assertTrue(re.match(r'ab(?<=b)c', 'abc'))
777n/a self.assertIsNone(re.match(r'ab(?<=c)c', 'abc'))
778n/a self.assertIsNone(re.match(r'ab(?<!b)c', 'abc'))
779n/a self.assertTrue(re.match(r'ab(?<!c)c', 'abc'))
780n/a # Group reference.
781n/a self.assertTrue(re.match(r'(a)a(?<=\1)c', 'aac'))
782n/a self.assertIsNone(re.match(r'(a)b(?<=\1)a', 'abaa'))
783n/a self.assertIsNone(re.match(r'(a)a(?<!\1)c', 'aac'))
784n/a self.assertTrue(re.match(r'(a)b(?<!\1)a', 'abaa'))
785n/a # Conditional group reference.
786n/a self.assertIsNone(re.match(r'(?:(a)|(x))b(?<=(?(2)x|c))c', 'abc'))
787n/a self.assertIsNone(re.match(r'(?:(a)|(x))b(?<=(?(2)b|x))c', 'abc'))
788n/a self.assertTrue(re.match(r'(?:(a)|(x))b(?<=(?(2)x|b))c', 'abc'))
789n/a self.assertIsNone(re.match(r'(?:(a)|(x))b(?<=(?(1)c|x))c', 'abc'))
790n/a self.assertTrue(re.match(r'(?:(a)|(x))b(?<=(?(1)b|x))c', 'abc'))
791n/a # Group used before defined.
792n/a self.assertRaises(re.error, re.compile, r'(a)b(?<=(?(2)b|x))(c)')
793n/a self.assertIsNone(re.match(r'(a)b(?<=(?(1)c|x))(c)', 'abc'))
794n/a self.assertTrue(re.match(r'(a)b(?<=(?(1)b|x))(c)', 'abc'))
795n/a # Group defined in the same lookbehind pattern
796n/a self.assertRaises(re.error, re.compile, r'(a)b(?<=(.)\2)(c)')
797n/a self.assertRaises(re.error, re.compile, r'(a)b(?<=(?P<a>.)(?P=a))(c)')
798n/a self.assertRaises(re.error, re.compile, r'(a)b(?<=(a)(?(2)b|x))(c)')
799n/a self.assertRaises(re.error, re.compile, r'(a)b(?<=(.)(?<=\2))(c)')
800n/a
801n/a def test_ignore_case(self):
802n/a self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
803n/a self.assertEqual(re.match(b"abc", b"ABC", re.I).group(0), b"ABC")
804n/a self.assertEqual(re.match(r"(a\s[^a])", "a b", re.I).group(1), "a b")
805n/a self.assertEqual(re.match(r"(a\s[^a]*)", "a bb", re.I).group(1), "a bb")
806n/a self.assertEqual(re.match(r"(a\s[abc])", "a b", re.I).group(1), "a b")
807n/a self.assertEqual(re.match(r"(a\s[abc]*)", "a bb", re.I).group(1), "a bb")
808n/a self.assertEqual(re.match(r"((a)\s\2)", "a a", re.I).group(1), "a a")
809n/a self.assertEqual(re.match(r"((a)\s\2*)", "a aa", re.I).group(1), "a aa")
810n/a self.assertEqual(re.match(r"((a)\s(abc|a))", "a a", re.I).group(1), "a a")
811n/a self.assertEqual(re.match(r"((a)\s(abc|a)*)", "a aa", re.I).group(1), "a aa")
812n/a
813n/a assert '\u212a'.lower() == 'k' # 'K'
814n/a self.assertTrue(re.match(r'K', '\u212a', re.I))
815n/a self.assertTrue(re.match(r'k', '\u212a', re.I))
816n/a self.assertTrue(re.match(r'\u212a', 'K', re.I))
817n/a self.assertTrue(re.match(r'\u212a', 'k', re.I))
818n/a assert '\u017f'.upper() == 'S' # 'Å¿'
819n/a self.assertTrue(re.match(r'S', '\u017f', re.I))
820n/a self.assertTrue(re.match(r's', '\u017f', re.I))
821n/a self.assertTrue(re.match(r'\u017f', 'S', re.I))
822n/a self.assertTrue(re.match(r'\u017f', 's', re.I))
823n/a assert '\ufb05'.upper() == '\ufb06'.upper() == 'ST' # 'ſt', 'st'
824n/a self.assertTrue(re.match(r'\ufb05', '\ufb06', re.I))
825n/a self.assertTrue(re.match(r'\ufb06', '\ufb05', re.I))
826n/a
827n/a def test_ignore_case_set(self):
828n/a self.assertTrue(re.match(r'[19A]', 'A', re.I))
829n/a self.assertTrue(re.match(r'[19a]', 'a', re.I))
830n/a self.assertTrue(re.match(r'[19a]', 'A', re.I))
831n/a self.assertTrue(re.match(r'[19A]', 'a', re.I))
832n/a self.assertTrue(re.match(br'[19A]', b'A', re.I))
833n/a self.assertTrue(re.match(br'[19a]', b'a', re.I))
834n/a self.assertTrue(re.match(br'[19a]', b'A', re.I))
835n/a self.assertTrue(re.match(br'[19A]', b'a', re.I))
836n/a assert '\u212a'.lower() == 'k' # 'K'
837n/a self.assertTrue(re.match(r'[19K]', '\u212a', re.I))
838n/a self.assertTrue(re.match(r'[19k]', '\u212a', re.I))
839n/a self.assertTrue(re.match(r'[19\u212a]', 'K', re.I))
840n/a self.assertTrue(re.match(r'[19\u212a]', 'k', re.I))
841n/a assert '\u017f'.upper() == 'S' # 'Å¿'
842n/a self.assertTrue(re.match(r'[19S]', '\u017f', re.I))
843n/a self.assertTrue(re.match(r'[19s]', '\u017f', re.I))
844n/a self.assertTrue(re.match(r'[19\u017f]', 'S', re.I))
845n/a self.assertTrue(re.match(r'[19\u017f]', 's', re.I))
846n/a assert '\ufb05'.upper() == '\ufb06'.upper() == 'ST' # 'ſt', 'st'
847n/a self.assertTrue(re.match(r'[19\ufb05]', '\ufb06', re.I))
848n/a self.assertTrue(re.match(r'[19\ufb06]', '\ufb05', re.I))
849n/a
850n/a def test_ignore_case_range(self):
851n/a # Issues #3511, #17381.
852n/a self.assertTrue(re.match(r'[9-a]', '_', re.I))
853n/a self.assertIsNone(re.match(r'[9-A]', '_', re.I))
854n/a self.assertTrue(re.match(br'[9-a]', b'_', re.I))
855n/a self.assertIsNone(re.match(br'[9-A]', b'_', re.I))
856n/a self.assertTrue(re.match(r'[\xc0-\xde]', '\xd7', re.I))
857n/a self.assertIsNone(re.match(r'[\xc0-\xde]', '\xf7', re.I))
858n/a self.assertTrue(re.match(r'[\xe0-\xfe]', '\xf7', re.I))
859n/a self.assertIsNone(re.match(r'[\xe0-\xfe]', '\xd7', re.I))
860n/a self.assertTrue(re.match(r'[\u0430-\u045f]', '\u0450', re.I))
861n/a self.assertTrue(re.match(r'[\u0430-\u045f]', '\u0400', re.I))
862n/a self.assertTrue(re.match(r'[\u0400-\u042f]', '\u0450', re.I))
863n/a self.assertTrue(re.match(r'[\u0400-\u042f]', '\u0400', re.I))
864n/a self.assertTrue(re.match(r'[\U00010428-\U0001044f]', '\U00010428', re.I))
865n/a self.assertTrue(re.match(r'[\U00010428-\U0001044f]', '\U00010400', re.I))
866n/a self.assertTrue(re.match(r'[\U00010400-\U00010427]', '\U00010428', re.I))
867n/a self.assertTrue(re.match(r'[\U00010400-\U00010427]', '\U00010400', re.I))
868n/a
869n/a assert '\u212a'.lower() == 'k' # 'K'
870n/a self.assertTrue(re.match(r'[J-M]', '\u212a', re.I))
871n/a self.assertTrue(re.match(r'[j-m]', '\u212a', re.I))
872n/a self.assertTrue(re.match(r'[\u2129-\u212b]', 'K', re.I))
873n/a self.assertTrue(re.match(r'[\u2129-\u212b]', 'k', re.I))
874n/a assert '\u017f'.upper() == 'S' # 'Å¿'
875n/a self.assertTrue(re.match(r'[R-T]', '\u017f', re.I))
876n/a self.assertTrue(re.match(r'[r-t]', '\u017f', re.I))
877n/a self.assertTrue(re.match(r'[\u017e-\u0180]', 'S', re.I))
878n/a self.assertTrue(re.match(r'[\u017e-\u0180]', 's', re.I))
879n/a assert '\ufb05'.upper() == '\ufb06'.upper() == 'ST' # 'ſt', 'st'
880n/a self.assertTrue(re.match(r'[\ufb04-\ufb05]', '\ufb06', re.I))
881n/a self.assertTrue(re.match(r'[\ufb06-\ufb07]', '\ufb05', re.I))
882n/a
883n/a def test_category(self):
884n/a self.assertEqual(re.match(r"(\s)", " ").group(1), " ")
885n/a
886n/a def test_getlower(self):
887n/a import _sre
888n/a self.assertEqual(_sre.getlower(ord('A'), 0), ord('a'))
889n/a self.assertEqual(_sre.getlower(ord('A'), re.LOCALE), ord('a'))
890n/a self.assertEqual(_sre.getlower(ord('A'), re.UNICODE), ord('a'))
891n/a self.assertEqual(_sre.getlower(ord('A'), re.ASCII), ord('a'))
892n/a
893n/a self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
894n/a self.assertEqual(re.match(b"abc", b"ABC", re.I).group(0), b"ABC")
895n/a self.assertEqual(re.match("abc", "ABC", re.I|re.A).group(0), "ABC")
896n/a self.assertEqual(re.match(b"abc", b"ABC", re.I|re.L).group(0), b"ABC")
897n/a
898n/a def test_not_literal(self):
899n/a self.assertEqual(re.search(r"\s([^a])", " b").group(1), "b")
900n/a self.assertEqual(re.search(r"\s([^a]*)", " bb").group(1), "bb")
901n/a
902n/a def test_search_coverage(self):
903n/a self.assertEqual(re.search(r"\s(b)", " b").group(1), "b")
904n/a self.assertEqual(re.search(r"a\s", "a ").group(0), "a ")
905n/a
906n/a def assertMatch(self, pattern, text, match=None, span=None,
907n/a matcher=re.match):
908n/a if match is None and span is None:
909n/a # the pattern matches the whole text
910n/a match = text
911n/a span = (0, len(text))
912n/a elif match is None or span is None:
913n/a raise ValueError('If match is not None, span should be specified '
914n/a '(and vice versa).')
915n/a m = matcher(pattern, text)
916n/a self.assertTrue(m)
917n/a self.assertEqual(m.group(), match)
918n/a self.assertEqual(m.span(), span)
919n/a
920n/a def test_re_escape(self):
921n/a alnum_chars = string.ascii_letters + string.digits + '_'
922n/a p = ''.join(chr(i) for i in range(256))
923n/a for c in p:
924n/a if c in alnum_chars:
925n/a self.assertEqual(re.escape(c), c)
926n/a elif c == '\x00':
927n/a self.assertEqual(re.escape(c), '\\000')
928n/a else:
929n/a self.assertEqual(re.escape(c), '\\' + c)
930n/a self.assertMatch(re.escape(c), c)
931n/a self.assertMatch(re.escape(p), p)
932n/a
933n/a def test_re_escape_byte(self):
934n/a alnum_chars = (string.ascii_letters + string.digits + '_').encode('ascii')
935n/a p = bytes(range(256))
936n/a for i in p:
937n/a b = bytes([i])
938n/a if b in alnum_chars:
939n/a self.assertEqual(re.escape(b), b)
940n/a elif i == 0:
941n/a self.assertEqual(re.escape(b), b'\\000')
942n/a else:
943n/a self.assertEqual(re.escape(b), b'\\' + b)
944n/a self.assertMatch(re.escape(b), b)
945n/a self.assertMatch(re.escape(p), p)
946n/a
947n/a def test_re_escape_non_ascii(self):
948n/a s = 'xxx\u2620\u2620\u2620xxx'
949n/a s_escaped = re.escape(s)
950n/a self.assertEqual(s_escaped, 'xxx\\\u2620\\\u2620\\\u2620xxx')
951n/a self.assertMatch(s_escaped, s)
952n/a self.assertMatch('.%s+.' % re.escape('\u2620'), s,
953n/a 'x\u2620\u2620\u2620x', (2, 7), re.search)
954n/a
955n/a def test_re_escape_non_ascii_bytes(self):
956n/a b = 'y\u2620y\u2620y'.encode('utf-8')
957n/a b_escaped = re.escape(b)
958n/a self.assertEqual(b_escaped, b'y\\\xe2\\\x98\\\xa0y\\\xe2\\\x98\\\xa0y')
959n/a self.assertMatch(b_escaped, b)
960n/a res = re.findall(re.escape('\u2620'.encode('utf-8')), b)
961n/a self.assertEqual(len(res), 2)
962n/a
963n/a def test_pickling(self):
964n/a import pickle
965n/a oldpat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)', re.UNICODE)
966n/a for proto in range(pickle.HIGHEST_PROTOCOL + 1):
967n/a pickled = pickle.dumps(oldpat, proto)
968n/a newpat = pickle.loads(pickled)
969n/a self.assertEqual(newpat, oldpat)
970n/a # current pickle expects the _compile() reconstructor in re module
971n/a from re import _compile
972n/a
973n/a def test_constants(self):
974n/a self.assertEqual(re.I, re.IGNORECASE)
975n/a self.assertEqual(re.L, re.LOCALE)
976n/a self.assertEqual(re.M, re.MULTILINE)
977n/a self.assertEqual(re.S, re.DOTALL)
978n/a self.assertEqual(re.X, re.VERBOSE)
979n/a
980n/a def test_flags(self):
981n/a for flag in [re.I, re.M, re.X, re.S, re.A, re.U]:
982n/a self.assertTrue(re.compile('^pattern$', flag))
983n/a for flag in [re.I, re.M, re.X, re.S, re.A, re.L]:
984n/a self.assertTrue(re.compile(b'^pattern$', flag))
985n/a
986n/a def test_sre_character_literals(self):
987n/a for i in [0, 8, 16, 32, 64, 127, 128, 255, 256, 0xFFFF, 0x10000, 0x10FFFF]:
988n/a if i < 256:
989n/a self.assertTrue(re.match(r"\%03o" % i, chr(i)))
990n/a self.assertTrue(re.match(r"\%03o0" % i, chr(i)+"0"))
991n/a self.assertTrue(re.match(r"\%03o8" % i, chr(i)+"8"))
992n/a self.assertTrue(re.match(r"\x%02x" % i, chr(i)))
993n/a self.assertTrue(re.match(r"\x%02x0" % i, chr(i)+"0"))
994n/a self.assertTrue(re.match(r"\x%02xz" % i, chr(i)+"z"))
995n/a if i < 0x10000:
996n/a self.assertTrue(re.match(r"\u%04x" % i, chr(i)))
997n/a self.assertTrue(re.match(r"\u%04x0" % i, chr(i)+"0"))
998n/a self.assertTrue(re.match(r"\u%04xz" % i, chr(i)+"z"))
999n/a self.assertTrue(re.match(r"\U%08x" % i, chr(i)))
1000n/a self.assertTrue(re.match(r"\U%08x0" % i, chr(i)+"0"))
1001n/a self.assertTrue(re.match(r"\U%08xz" % i, chr(i)+"z"))
1002n/a self.assertTrue(re.match(r"\0", "\000"))
1003n/a self.assertTrue(re.match(r"\08", "\0008"))
1004n/a self.assertTrue(re.match(r"\01", "\001"))
1005n/a self.assertTrue(re.match(r"\018", "\0018"))
1006n/a self.checkPatternError(r"\567",
1007n/a r'octal escape value \567 outside of '
1008n/a r'range 0-0o377', 0)
1009n/a self.checkPatternError(r"\911", 'invalid group reference 91', 1)
1010n/a self.checkPatternError(r"\x1", r'incomplete escape \x1', 0)
1011n/a self.checkPatternError(r"\x1z", r'incomplete escape \x1', 0)
1012n/a self.checkPatternError(r"\u123", r'incomplete escape \u123', 0)
1013n/a self.checkPatternError(r"\u123z", r'incomplete escape \u123', 0)
1014n/a self.checkPatternError(r"\U0001234", r'incomplete escape \U0001234', 0)
1015n/a self.checkPatternError(r"\U0001234z", r'incomplete escape \U0001234', 0)
1016n/a self.checkPatternError(r"\U00110000", r'bad escape \U00110000', 0)
1017n/a
1018n/a def test_sre_character_class_literals(self):
1019n/a for i in [0, 8, 16, 32, 64, 127, 128, 255, 256, 0xFFFF, 0x10000, 0x10FFFF]:
1020n/a if i < 256:
1021n/a self.assertTrue(re.match(r"[\%o]" % i, chr(i)))
1022n/a self.assertTrue(re.match(r"[\%o8]" % i, chr(i)))
1023n/a self.assertTrue(re.match(r"[\%03o]" % i, chr(i)))
1024n/a self.assertTrue(re.match(r"[\%03o0]" % i, chr(i)))
1025n/a self.assertTrue(re.match(r"[\%03o8]" % i, chr(i)))
1026n/a self.assertTrue(re.match(r"[\x%02x]" % i, chr(i)))
1027n/a self.assertTrue(re.match(r"[\x%02x0]" % i, chr(i)))
1028n/a self.assertTrue(re.match(r"[\x%02xz]" % i, chr(i)))
1029n/a if i < 0x10000:
1030n/a self.assertTrue(re.match(r"[\u%04x]" % i, chr(i)))
1031n/a self.assertTrue(re.match(r"[\u%04x0]" % i, chr(i)))
1032n/a self.assertTrue(re.match(r"[\u%04xz]" % i, chr(i)))
1033n/a self.assertTrue(re.match(r"[\U%08x]" % i, chr(i)))
1034n/a self.assertTrue(re.match(r"[\U%08x0]" % i, chr(i)+"0"))
1035n/a self.assertTrue(re.match(r"[\U%08xz]" % i, chr(i)+"z"))
1036n/a self.checkPatternError(r"[\567]",
1037n/a r'octal escape value \567 outside of '
1038n/a r'range 0-0o377', 1)
1039n/a self.checkPatternError(r"[\911]", r'bad escape \9', 1)
1040n/a self.checkPatternError(r"[\x1z]", r'incomplete escape \x1', 1)
1041n/a self.checkPatternError(r"[\u123z]", r'incomplete escape \u123', 1)
1042n/a self.checkPatternError(r"[\U0001234z]", r'incomplete escape \U0001234', 1)
1043n/a self.checkPatternError(r"[\U00110000]", r'bad escape \U00110000', 1)
1044n/a self.assertTrue(re.match(r"[\U0001d49c-\U0001d4b5]", "\U0001d49e"))
1045n/a
1046n/a def test_sre_byte_literals(self):
1047n/a for i in [0, 8, 16, 32, 64, 127, 128, 255]:
1048n/a self.assertTrue(re.match((r"\%03o" % i).encode(), bytes([i])))
1049n/a self.assertTrue(re.match((r"\%03o0" % i).encode(), bytes([i])+b"0"))
1050n/a self.assertTrue(re.match((r"\%03o8" % i).encode(), bytes([i])+b"8"))
1051n/a self.assertTrue(re.match((r"\x%02x" % i).encode(), bytes([i])))
1052n/a self.assertTrue(re.match((r"\x%02x0" % i).encode(), bytes([i])+b"0"))
1053n/a self.assertTrue(re.match((r"\x%02xz" % i).encode(), bytes([i])+b"z"))
1054n/a self.assertRaises(re.error, re.compile, br"\u1234")
1055n/a self.assertRaises(re.error, re.compile, br"\U00012345")
1056n/a self.assertTrue(re.match(br"\0", b"\000"))
1057n/a self.assertTrue(re.match(br"\08", b"\0008"))
1058n/a self.assertTrue(re.match(br"\01", b"\001"))
1059n/a self.assertTrue(re.match(br"\018", b"\0018"))
1060n/a self.checkPatternError(br"\567",
1061n/a r'octal escape value \567 outside of '
1062n/a r'range 0-0o377', 0)
1063n/a self.checkPatternError(br"\911", 'invalid group reference 91', 1)
1064n/a self.checkPatternError(br"\x1", r'incomplete escape \x1', 0)
1065n/a self.checkPatternError(br"\x1z", r'incomplete escape \x1', 0)
1066n/a
1067n/a def test_sre_byte_class_literals(self):
1068n/a for i in [0, 8, 16, 32, 64, 127, 128, 255]:
1069n/a self.assertTrue(re.match((r"[\%o]" % i).encode(), bytes([i])))
1070n/a self.assertTrue(re.match((r"[\%o8]" % i).encode(), bytes([i])))
1071n/a self.assertTrue(re.match((r"[\%03o]" % i).encode(), bytes([i])))
1072n/a self.assertTrue(re.match((r"[\%03o0]" % i).encode(), bytes([i])))
1073n/a self.assertTrue(re.match((r"[\%03o8]" % i).encode(), bytes([i])))
1074n/a self.assertTrue(re.match((r"[\x%02x]" % i).encode(), bytes([i])))
1075n/a self.assertTrue(re.match((r"[\x%02x0]" % i).encode(), bytes([i])))
1076n/a self.assertTrue(re.match((r"[\x%02xz]" % i).encode(), bytes([i])))
1077n/a self.assertRaises(re.error, re.compile, br"[\u1234]")
1078n/a self.assertRaises(re.error, re.compile, br"[\U00012345]")
1079n/a self.checkPatternError(br"[\567]",
1080n/a r'octal escape value \567 outside of '
1081n/a r'range 0-0o377', 1)
1082n/a self.checkPatternError(br"[\911]", r'bad escape \9', 1)
1083n/a self.checkPatternError(br"[\x1z]", r'incomplete escape \x1', 1)
1084n/a
1085n/a def test_character_set_errors(self):
1086n/a self.checkPatternError(r'[', 'unterminated character set', 0)
1087n/a self.checkPatternError(r'[^', 'unterminated character set', 0)
1088n/a self.checkPatternError(r'[a', 'unterminated character set', 0)
1089n/a # bug 545855 -- This pattern failed to cause a compile error as it
1090n/a # should, instead provoking a TypeError.
1091n/a self.checkPatternError(r"[a-", 'unterminated character set', 0)
1092n/a self.checkPatternError(r"[\w-b]", r'bad character range \w-b', 1)
1093n/a self.checkPatternError(r"[a-\w]", r'bad character range a-\w', 1)
1094n/a self.checkPatternError(r"[b-a]", 'bad character range b-a', 1)
1095n/a
1096n/a def test_bug_113254(self):
1097n/a self.assertEqual(re.match(r'(a)|(b)', 'b').start(1), -1)
1098n/a self.assertEqual(re.match(r'(a)|(b)', 'b').end(1), -1)
1099n/a self.assertEqual(re.match(r'(a)|(b)', 'b').span(1), (-1, -1))
1100n/a
1101n/a def test_bug_527371(self):
1102n/a # bug described in patches 527371/672491
1103n/a self.assertIsNone(re.match(r'(a)?a','a').lastindex)
1104n/a self.assertEqual(re.match(r'(a)(b)?b','ab').lastindex, 1)
1105n/a self.assertEqual(re.match(r'(?P<a>a)(?P<b>b)?b','ab').lastgroup, 'a')
1106n/a self.assertEqual(re.match(r"(?P<a>a(b))", "ab").lastgroup, 'a')
1107n/a self.assertEqual(re.match(r"((a))", "a").lastindex, 1)
1108n/a
1109n/a def test_bug_418626(self):
1110n/a # bugs 418626 at al. -- Testing Greg Chapman's addition of op code
1111n/a # SRE_OP_MIN_REPEAT_ONE for eliminating recursion on simple uses of
1112n/a # pattern '*?' on a long string.
1113n/a self.assertEqual(re.match('.*?c', 10000*'ab'+'cd').end(0), 20001)
1114n/a self.assertEqual(re.match('.*?cd', 5000*'ab'+'c'+5000*'ab'+'cde').end(0),
1115n/a 20003)
1116n/a self.assertEqual(re.match('.*?cd', 20000*'abc'+'de').end(0), 60001)
1117n/a # non-simple '*?' still used to hit the recursion limit, before the
1118n/a # non-recursive scheme was implemented.
1119n/a self.assertEqual(re.search('(a|b)*?c', 10000*'ab'+'cd').end(0), 20001)
1120n/a
1121n/a def test_bug_612074(self):
1122n/a pat="["+re.escape("\u2039")+"]"
1123n/a self.assertEqual(re.compile(pat) and 1, 1)
1124n/a
1125n/a def test_stack_overflow(self):
1126n/a # nasty cases that used to overflow the straightforward recursive
1127n/a # implementation of repeated groups.
1128n/a self.assertEqual(re.match('(x)*', 50000*'x').group(1), 'x')
1129n/a self.assertEqual(re.match('(x)*y', 50000*'x'+'y').group(1), 'x')
1130n/a self.assertEqual(re.match('(x)*?y', 50000*'x'+'y').group(1), 'x')
1131n/a
1132n/a def test_nothing_to_repeat(self):
1133n/a for reps in '*', '+', '?', '{1,2}':
1134n/a for mod in '', '?':
1135n/a self.checkPatternError('%s%s' % (reps, mod),
1136n/a 'nothing to repeat', 0)
1137n/a self.checkPatternError('(?:%s%s)' % (reps, mod),
1138n/a 'nothing to repeat', 3)
1139n/a
1140n/a def test_multiple_repeat(self):
1141n/a for outer_reps in '*', '+', '{1,2}':
1142n/a for outer_mod in '', '?':
1143n/a outer_op = outer_reps + outer_mod
1144n/a for inner_reps in '*', '+', '?', '{1,2}':
1145n/a for inner_mod in '', '?':
1146n/a inner_op = inner_reps + inner_mod
1147n/a self.checkPatternError(r'x%s%s' % (inner_op, outer_op),
1148n/a 'multiple repeat', 1 + len(inner_op))
1149n/a
1150n/a def test_unlimited_zero_width_repeat(self):
1151n/a # Issue #9669
1152n/a self.assertIsNone(re.match(r'(?:a?)*y', 'z'))
1153n/a self.assertIsNone(re.match(r'(?:a?)+y', 'z'))
1154n/a self.assertIsNone(re.match(r'(?:a?){2,}y', 'z'))
1155n/a self.assertIsNone(re.match(r'(?:a?)*?y', 'z'))
1156n/a self.assertIsNone(re.match(r'(?:a?)+?y', 'z'))
1157n/a self.assertIsNone(re.match(r'(?:a?){2,}?y', 'z'))
1158n/a
1159n/a def test_scanner(self):
1160n/a def s_ident(scanner, token): return token
1161n/a def s_operator(scanner, token): return "op%s" % token
1162n/a def s_float(scanner, token): return float(token)
1163n/a def s_int(scanner, token): return int(token)
1164n/a
1165n/a scanner = Scanner([
1166n/a (r"[a-zA-Z_]\w*", s_ident),
1167n/a (r"\d+\.\d*", s_float),
1168n/a (r"\d+", s_int),
1169n/a (r"=|\+|-|\*|/", s_operator),
1170n/a (r"\s+", None),
1171n/a ])
1172n/a
1173n/a self.assertTrue(scanner.scanner.scanner("").pattern)
1174n/a
1175n/a self.assertEqual(scanner.scan("sum = 3*foo + 312.50 + bar"),
1176n/a (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5,
1177n/a 'op+', 'bar'], ''))
1178n/a
1179n/a def test_bug_448951(self):
1180n/a # bug 448951 (similar to 429357, but with single char match)
1181n/a # (Also test greedy matches.)
1182n/a for op in '','?','*':
1183n/a self.assertEqual(re.match(r'((.%s):)?z'%op, 'z').groups(),
1184n/a (None, None))
1185n/a self.assertEqual(re.match(r'((.%s):)?z'%op, 'a:z').groups(),
1186n/a ('a:', 'a'))
1187n/a
1188n/a def test_bug_725106(self):
1189n/a # capturing groups in alternatives in repeats
1190n/a self.assertEqual(re.match('^((a)|b)*', 'abc').groups(),
1191n/a ('b', 'a'))
1192n/a self.assertEqual(re.match('^(([ab])|c)*', 'abc').groups(),
1193n/a ('c', 'b'))
1194n/a self.assertEqual(re.match('^((d)|[ab])*', 'abc').groups(),
1195n/a ('b', None))
1196n/a self.assertEqual(re.match('^((a)c|[ab])*', 'abc').groups(),
1197n/a ('b', None))
1198n/a self.assertEqual(re.match('^((a)|b)*?c', 'abc').groups(),
1199n/a ('b', 'a'))
1200n/a self.assertEqual(re.match('^(([ab])|c)*?d', 'abcd').groups(),
1201n/a ('c', 'b'))
1202n/a self.assertEqual(re.match('^((d)|[ab])*?c', 'abc').groups(),
1203n/a ('b', None))
1204n/a self.assertEqual(re.match('^((a)c|[ab])*?c', 'abc').groups(),
1205n/a ('b', None))
1206n/a
1207n/a def test_bug_725149(self):
1208n/a # mark_stack_base restoring before restoring marks
1209n/a self.assertEqual(re.match('(a)(?:(?=(b)*)c)*', 'abb').groups(),
1210n/a ('a', None))
1211n/a self.assertEqual(re.match('(a)((?!(b)*))*', 'abb').groups(),
1212n/a ('a', None, None))
1213n/a
1214n/a def test_bug_764548(self):
1215n/a # bug 764548, re.compile() barfs on str/unicode subclasses
1216n/a class my_unicode(str): pass
1217n/a pat = re.compile(my_unicode("abc"))
1218n/a self.assertIsNone(pat.match("xyz"))
1219n/a
1220n/a def test_finditer(self):
1221n/a iter = re.finditer(r":+", "a:b::c:::d")
1222n/a self.assertEqual([item.group(0) for item in iter],
1223n/a [":", "::", ":::"])
1224n/a
1225n/a pat = re.compile(r":+")
1226n/a iter = pat.finditer("a:b::c:::d", 1, 10)
1227n/a self.assertEqual([item.group(0) for item in iter],
1228n/a [":", "::", ":::"])
1229n/a
1230n/a pat = re.compile(r":+")
1231n/a iter = pat.finditer("a:b::c:::d", pos=1, endpos=10)
1232n/a self.assertEqual([item.group(0) for item in iter],
1233n/a [":", "::", ":::"])
1234n/a
1235n/a pat = re.compile(r":+")
1236n/a iter = pat.finditer("a:b::c:::d", endpos=10, pos=1)
1237n/a self.assertEqual([item.group(0) for item in iter],
1238n/a [":", "::", ":::"])
1239n/a
1240n/a pat = re.compile(r":+")
1241n/a iter = pat.finditer("a:b::c:::d", pos=3, endpos=8)
1242n/a self.assertEqual([item.group(0) for item in iter],
1243n/a ["::", "::"])
1244n/a
1245n/a def test_bug_926075(self):
1246n/a self.assertIsNot(re.compile('bug_926075'),
1247n/a re.compile(b'bug_926075'))
1248n/a
1249n/a def test_bug_931848(self):
1250n/a pattern = "[\u002E\u3002\uFF0E\uFF61]"
1251n/a self.assertEqual(re.compile(pattern).split("a.b.c"),
1252n/a ['a','b','c'])
1253n/a
1254n/a def test_bug_581080(self):
1255n/a iter = re.finditer(r"\s", "a b")
1256n/a self.assertEqual(next(iter).span(), (1,2))
1257n/a self.assertRaises(StopIteration, next, iter)
1258n/a
1259n/a scanner = re.compile(r"\s").scanner("a b")
1260n/a self.assertEqual(scanner.search().span(), (1, 2))
1261n/a self.assertIsNone(scanner.search())
1262n/a
1263n/a def test_bug_817234(self):
1264n/a iter = re.finditer(r".*", "asdf")
1265n/a self.assertEqual(next(iter).span(), (0, 4))
1266n/a self.assertEqual(next(iter).span(), (4, 4))
1267n/a self.assertRaises(StopIteration, next, iter)
1268n/a
1269n/a def test_bug_6561(self):
1270n/a # '\d' should match characters in Unicode category 'Nd'
1271n/a # (Number, Decimal Digit), but not those in 'Nl' (Number,
1272n/a # Letter) or 'No' (Number, Other).
1273n/a decimal_digits = [
1274n/a '\u0037', # '\N{DIGIT SEVEN}', category 'Nd'
1275n/a '\u0e58', # '\N{THAI DIGIT SIX}', category 'Nd'
1276n/a '\uff10', # '\N{FULLWIDTH DIGIT ZERO}', category 'Nd'
1277n/a ]
1278n/a for x in decimal_digits:
1279n/a self.assertEqual(re.match(r'^\d$', x).group(0), x)
1280n/a
1281n/a not_decimal_digits = [
1282n/a '\u2165', # '\N{ROMAN NUMERAL SIX}', category 'Nl'
1283n/a '\u3039', # '\N{HANGZHOU NUMERAL TWENTY}', category 'Nl'
1284n/a '\u2082', # '\N{SUBSCRIPT TWO}', category 'No'
1285n/a '\u32b4', # '\N{CIRCLED NUMBER THIRTY NINE}', category 'No'
1286n/a ]
1287n/a for x in not_decimal_digits:
1288n/a self.assertIsNone(re.match(r'^\d$', x))
1289n/a
1290n/a def test_empty_array(self):
1291n/a # SF buf 1647541
1292n/a import array
1293n/a for typecode in 'bBuhHiIlLfd':
1294n/a a = array.array(typecode)
1295n/a self.assertIsNone(re.compile(b"bla").match(a))
1296n/a self.assertEqual(re.compile(b"").match(a).groups(), ())
1297n/a
1298n/a def test_inline_flags(self):
1299n/a # Bug #1700
1300n/a upper_char = '\u1ea0' # Latin Capital Letter A with Dot Below
1301n/a lower_char = '\u1ea1' # Latin Small Letter A with Dot Below
1302n/a
1303n/a p = re.compile(upper_char, re.I | re.U)
1304n/a q = p.match(lower_char)
1305n/a self.assertTrue(q)
1306n/a
1307n/a p = re.compile(lower_char, re.I | re.U)
1308n/a q = p.match(upper_char)
1309n/a self.assertTrue(q)
1310n/a
1311n/a p = re.compile('(?i)' + upper_char, re.U)
1312n/a q = p.match(lower_char)
1313n/a self.assertTrue(q)
1314n/a
1315n/a p = re.compile('(?i)' + lower_char, re.U)
1316n/a q = p.match(upper_char)
1317n/a self.assertTrue(q)
1318n/a
1319n/a p = re.compile('(?iu)' + upper_char)
1320n/a q = p.match(lower_char)
1321n/a self.assertTrue(q)
1322n/a
1323n/a p = re.compile('(?iu)' + lower_char)
1324n/a q = p.match(upper_char)
1325n/a self.assertTrue(q)
1326n/a
1327n/a self.assertTrue(re.match('(?ixu) ' + upper_char, lower_char))
1328n/a self.assertTrue(re.match('(?ixu) ' + lower_char, upper_char))
1329n/a
1330n/a p = upper_char + '(?i)'
1331n/a with self.assertWarns(DeprecationWarning) as warns:
1332n/a self.assertTrue(re.match(p, lower_char))
1333n/a self.assertEqual(
1334n/a str(warns.warnings[0].message),
1335n/a 'Flags not at the start of the expression %s' % p
1336n/a )
1337n/a
1338n/a p = upper_char + '(?i)%s' % ('.?' * 100)
1339n/a with self.assertWarns(DeprecationWarning) as warns:
1340n/a self.assertTrue(re.match(p, lower_char))
1341n/a self.assertEqual(
1342n/a str(warns.warnings[0].message),
1343n/a 'Flags not at the start of the expression %s (truncated)' % p[:20]
1344n/a )
1345n/a
1346n/a def test_dollar_matches_twice(self):
1347n/a "$ matches the end of string, and just before the terminating \n"
1348n/a pattern = re.compile('$')
1349n/a self.assertEqual(pattern.sub('#', 'a\nb\n'), 'a\nb#\n#')
1350n/a self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a\nb\nc#')
1351n/a self.assertEqual(pattern.sub('#', '\n'), '#\n#')
1352n/a
1353n/a pattern = re.compile('$', re.MULTILINE)
1354n/a self.assertEqual(pattern.sub('#', 'a\nb\n' ), 'a#\nb#\n#' )
1355n/a self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a#\nb#\nc#')
1356n/a self.assertEqual(pattern.sub('#', '\n'), '#\n#')
1357n/a
1358n/a def test_bytes_str_mixing(self):
1359n/a # Mixing str and bytes is disallowed
1360n/a pat = re.compile('.')
1361n/a bpat = re.compile(b'.')
1362n/a self.assertRaises(TypeError, pat.match, b'b')
1363n/a self.assertRaises(TypeError, bpat.match, 'b')
1364n/a self.assertRaises(TypeError, pat.sub, b'b', 'c')
1365n/a self.assertRaises(TypeError, pat.sub, 'b', b'c')
1366n/a self.assertRaises(TypeError, pat.sub, b'b', b'c')
1367n/a self.assertRaises(TypeError, bpat.sub, b'b', 'c')
1368n/a self.assertRaises(TypeError, bpat.sub, 'b', b'c')
1369n/a self.assertRaises(TypeError, bpat.sub, 'b', 'c')
1370n/a
1371n/a def test_ascii_and_unicode_flag(self):
1372n/a # String patterns
1373n/a for flags in (0, re.UNICODE):
1374n/a pat = re.compile('\xc0', flags | re.IGNORECASE)
1375n/a self.assertTrue(pat.match('\xe0'))
1376n/a pat = re.compile(r'\w', flags)
1377n/a self.assertTrue(pat.match('\xe0'))
1378n/a pat = re.compile('\xc0', re.ASCII | re.IGNORECASE)
1379n/a self.assertIsNone(pat.match('\xe0'))
1380n/a pat = re.compile('(?a)\xc0', re.IGNORECASE)
1381n/a self.assertIsNone(pat.match('\xe0'))
1382n/a pat = re.compile(r'\w', re.ASCII)
1383n/a self.assertIsNone(pat.match('\xe0'))
1384n/a pat = re.compile(r'(?a)\w')
1385n/a self.assertIsNone(pat.match('\xe0'))
1386n/a # Bytes patterns
1387n/a for flags in (0, re.ASCII):
1388n/a pat = re.compile(b'\xc0', flags | re.IGNORECASE)
1389n/a self.assertIsNone(pat.match(b'\xe0'))
1390n/a pat = re.compile(br'\w', flags)
1391n/a self.assertIsNone(pat.match(b'\xe0'))
1392n/a # Incompatibilities
1393n/a self.assertRaises(ValueError, re.compile, br'\w', re.UNICODE)
1394n/a self.assertRaises(ValueError, re.compile, br'(?u)\w')
1395n/a self.assertRaises(ValueError, re.compile, r'\w', re.UNICODE | re.ASCII)
1396n/a self.assertRaises(ValueError, re.compile, r'(?u)\w', re.ASCII)
1397n/a self.assertRaises(ValueError, re.compile, r'(?a)\w', re.UNICODE)
1398n/a self.assertRaises(ValueError, re.compile, r'(?au)\w')
1399n/a
1400n/a def test_locale_flag(self):
1401n/a import locale
1402n/a _, enc = locale.getlocale(locale.LC_CTYPE)
1403n/a # Search non-ASCII letter
1404n/a for i in range(128, 256):
1405n/a try:
1406n/a c = bytes([i]).decode(enc)
1407n/a sletter = c.lower()
1408n/a if sletter == c: continue
1409n/a bletter = sletter.encode(enc)
1410n/a if len(bletter) != 1: continue
1411n/a if bletter.decode(enc) != sletter: continue
1412n/a bpat = re.escape(bytes([i]))
1413n/a break
1414n/a except (UnicodeError, TypeError):
1415n/a pass
1416n/a else:
1417n/a bletter = None
1418n/a bpat = b'A'
1419n/a # Bytes patterns
1420n/a pat = re.compile(bpat, re.LOCALE | re.IGNORECASE)
1421n/a if bletter:
1422n/a self.assertTrue(pat.match(bletter))
1423n/a pat = re.compile(b'(?L)' + bpat, re.IGNORECASE)
1424n/a if bletter:
1425n/a self.assertTrue(pat.match(bletter))
1426n/a pat = re.compile(bpat, re.IGNORECASE)
1427n/a if bletter:
1428n/a self.assertIsNone(pat.match(bletter))
1429n/a pat = re.compile(br'\w', re.LOCALE)
1430n/a if bletter:
1431n/a self.assertTrue(pat.match(bletter))
1432n/a pat = re.compile(br'(?L)\w')
1433n/a if bletter:
1434n/a self.assertTrue(pat.match(bletter))
1435n/a pat = re.compile(br'\w')
1436n/a if bletter:
1437n/a self.assertIsNone(pat.match(bletter))
1438n/a # Incompatibilities
1439n/a self.assertRaises(ValueError, re.compile, '', re.LOCALE)
1440n/a self.assertRaises(ValueError, re.compile, '(?L)')
1441n/a self.assertRaises(ValueError, re.compile, b'', re.LOCALE | re.ASCII)
1442n/a self.assertRaises(ValueError, re.compile, b'(?L)', re.ASCII)
1443n/a self.assertRaises(ValueError, re.compile, b'(?a)', re.LOCALE)
1444n/a self.assertRaises(ValueError, re.compile, b'(?aL)')
1445n/a
1446n/a def test_scoped_flags(self):
1447n/a self.assertTrue(re.match(r'(?i:a)b', 'Ab'))
1448n/a self.assertIsNone(re.match(r'(?i:a)b', 'aB'))
1449n/a self.assertIsNone(re.match(r'(?-i:a)b', 'Ab', re.IGNORECASE))
1450n/a self.assertTrue(re.match(r'(?-i:a)b', 'aB', re.IGNORECASE))
1451n/a self.assertIsNone(re.match(r'(?i:(?-i:a)b)', 'Ab'))
1452n/a self.assertTrue(re.match(r'(?i:(?-i:a)b)', 'aB'))
1453n/a
1454n/a self.assertTrue(re.match(r'(?x: a) b', 'a b'))
1455n/a self.assertIsNone(re.match(r'(?x: a) b', ' a b'))
1456n/a self.assertTrue(re.match(r'(?-x: a) b', ' ab', re.VERBOSE))
1457n/a self.assertIsNone(re.match(r'(?-x: a) b', 'ab', re.VERBOSE))
1458n/a
1459n/a self.checkPatternError(r'(?a:\w)',
1460n/a 'bad inline flags: cannot turn on global flag', 3)
1461n/a self.checkPatternError(r'(?a)(?-a:\w)',
1462n/a 'bad inline flags: cannot turn off global flag', 8)
1463n/a self.checkPatternError(r'(?i-i:a)',
1464n/a 'bad inline flags: flag turned on and off', 5)
1465n/a
1466n/a self.checkPatternError(r'(?-', 'missing flag', 3)
1467n/a self.checkPatternError(r'(?-+', 'missing flag', 3)
1468n/a self.checkPatternError(r'(?-z', 'unknown flag', 3)
1469n/a self.checkPatternError(r'(?-i', 'missing :', 4)
1470n/a self.checkPatternError(r'(?-i)', 'missing :', 4)
1471n/a self.checkPatternError(r'(?-i+', 'missing :', 4)
1472n/a self.checkPatternError(r'(?-iz', 'unknown flag', 4)
1473n/a self.checkPatternError(r'(?i:', 'missing ), unterminated subpattern', 0)
1474n/a self.checkPatternError(r'(?i', 'missing -, : or )', 3)
1475n/a self.checkPatternError(r'(?i+', 'missing -, : or )', 3)
1476n/a self.checkPatternError(r'(?iz', 'unknown flag', 3)
1477n/a
1478n/a def test_bug_6509(self):
1479n/a # Replacement strings of both types must parse properly.
1480n/a # all strings
1481n/a pat = re.compile(r'a(\w)')
1482n/a self.assertEqual(pat.sub('b\\1', 'ac'), 'bc')
1483n/a pat = re.compile('a(.)')
1484n/a self.assertEqual(pat.sub('b\\1', 'a\u1234'), 'b\u1234')
1485n/a pat = re.compile('..')
1486n/a self.assertEqual(pat.sub(lambda m: 'str', 'a5'), 'str')
1487n/a
1488n/a # all bytes
1489n/a pat = re.compile(br'a(\w)')
1490n/a self.assertEqual(pat.sub(b'b\\1', b'ac'), b'bc')
1491n/a pat = re.compile(b'a(.)')
1492n/a self.assertEqual(pat.sub(b'b\\1', b'a\xCD'), b'b\xCD')
1493n/a pat = re.compile(b'..')
1494n/a self.assertEqual(pat.sub(lambda m: b'bytes', b'a5'), b'bytes')
1495n/a
1496n/a def test_dealloc(self):
1497n/a # issue 3299: check for segfault in debug build
1498n/a import _sre
1499n/a # the overflow limit is different on wide and narrow builds and it
1500n/a # depends on the definition of SRE_CODE (see sre.h).
1501n/a # 2**128 should be big enough to overflow on both. For smaller values
1502n/a # a RuntimeError is raised instead of OverflowError.
1503n/a long_overflow = 2**128
1504n/a self.assertRaises(TypeError, re.finditer, "a", {})
1505n/a with self.assertRaises(OverflowError):
1506n/a _sre.compile("abc", 0, [long_overflow], 0, {}, ())
1507n/a with self.assertRaises(TypeError):
1508n/a _sre.compile({}, 0, [], 0, [], [])
1509n/a
1510n/a def test_search_dot_unicode(self):
1511n/a self.assertTrue(re.search("123.*-", '123abc-'))
1512n/a self.assertTrue(re.search("123.*-", '123\xe9-'))
1513n/a self.assertTrue(re.search("123.*-", '123\u20ac-'))
1514n/a self.assertTrue(re.search("123.*-", '123\U0010ffff-'))
1515n/a self.assertTrue(re.search("123.*-", '123\xe9\u20ac\U0010ffff-'))
1516n/a
1517n/a def test_compile(self):
1518n/a # Test return value when given string and pattern as parameter
1519n/a pattern = re.compile('random pattern')
1520n/a self.assertIsInstance(pattern, re._pattern_type)
1521n/a same_pattern = re.compile(pattern)
1522n/a self.assertIsInstance(same_pattern, re._pattern_type)
1523n/a self.assertIs(same_pattern, pattern)
1524n/a # Test behaviour when not given a string or pattern as parameter
1525n/a self.assertRaises(TypeError, re.compile, 0)
1526n/a
1527n/a @bigmemtest(size=_2G, memuse=1)
1528n/a def test_large_search(self, size):
1529n/a # Issue #10182: indices were 32-bit-truncated.
1530n/a s = 'a' * size
1531n/a m = re.search('$', s)
1532n/a self.assertIsNotNone(m)
1533n/a self.assertEqual(m.start(), size)
1534n/a self.assertEqual(m.end(), size)
1535n/a
1536n/a # The huge memuse is because of re.sub() using a list and a join()
1537n/a # to create the replacement result.
1538n/a @bigmemtest(size=_2G, memuse=16 + 2)
1539n/a def test_large_subn(self, size):
1540n/a # Issue #10182: indices were 32-bit-truncated.
1541n/a s = 'a' * size
1542n/a r, n = re.subn('', '', s)
1543n/a self.assertEqual(r, s)
1544n/a self.assertEqual(n, size + 1)
1545n/a
1546n/a def test_bug_16688(self):
1547n/a # Issue 16688: Backreferences make case-insensitive regex fail on
1548n/a # non-ASCII strings.
1549n/a self.assertEqual(re.findall(r"(?i)(a)\1", "aa \u0100"), ['a'])
1550n/a self.assertEqual(re.match(r"(?s).{1,3}", "\u0100\u0100").span(), (0, 2))
1551n/a
1552n/a def test_repeat_minmax_overflow(self):
1553n/a # Issue #13169
1554n/a string = "x" * 100000
1555n/a self.assertEqual(re.match(r".{65535}", string).span(), (0, 65535))
1556n/a self.assertEqual(re.match(r".{,65535}", string).span(), (0, 65535))
1557n/a self.assertEqual(re.match(r".{65535,}?", string).span(), (0, 65535))
1558n/a self.assertEqual(re.match(r".{65536}", string).span(), (0, 65536))
1559n/a self.assertEqual(re.match(r".{,65536}", string).span(), (0, 65536))
1560n/a self.assertEqual(re.match(r".{65536,}?", string).span(), (0, 65536))
1561n/a # 2**128 should be big enough to overflow both SRE_CODE and Py_ssize_t.
1562n/a self.assertRaises(OverflowError, re.compile, r".{%d}" % 2**128)
1563n/a self.assertRaises(OverflowError, re.compile, r".{,%d}" % 2**128)
1564n/a self.assertRaises(OverflowError, re.compile, r".{%d,}?" % 2**128)
1565n/a self.assertRaises(OverflowError, re.compile, r".{%d,%d}" % (2**129, 2**128))
1566n/a
1567n/a @cpython_only
1568n/a def test_repeat_minmax_overflow_maxrepeat(self):
1569n/a try:
1570n/a from _sre import MAXREPEAT
1571n/a except ImportError:
1572n/a self.skipTest('requires _sre.MAXREPEAT constant')
1573n/a string = "x" * 100000
1574n/a self.assertIsNone(re.match(r".{%d}" % (MAXREPEAT - 1), string))
1575n/a self.assertEqual(re.match(r".{,%d}" % (MAXREPEAT - 1), string).span(),
1576n/a (0, 100000))
1577n/a self.assertIsNone(re.match(r".{%d,}?" % (MAXREPEAT - 1), string))
1578n/a self.assertRaises(OverflowError, re.compile, r".{%d}" % MAXREPEAT)
1579n/a self.assertRaises(OverflowError, re.compile, r".{,%d}" % MAXREPEAT)
1580n/a self.assertRaises(OverflowError, re.compile, r".{%d,}?" % MAXREPEAT)
1581n/a
1582n/a def test_backref_group_name_in_exception(self):
1583n/a # Issue 17341: Poor error message when compiling invalid regex
1584n/a self.checkPatternError('(?P=<foo>)',
1585n/a "bad character in group name '<foo>'", 4)
1586n/a
1587n/a def test_group_name_in_exception(self):
1588n/a # Issue 17341: Poor error message when compiling invalid regex
1589n/a self.checkPatternError('(?P<?foo>)',
1590n/a "bad character in group name '?foo'", 4)
1591n/a
1592n/a def test_issue17998(self):
1593n/a for reps in '*', '+', '?', '{1}':
1594n/a for mod in '', '?':
1595n/a pattern = '.' + reps + mod + 'yz'
1596n/a self.assertEqual(re.compile(pattern, re.S).findall('xyz'),
1597n/a ['xyz'], msg=pattern)
1598n/a pattern = pattern.encode()
1599n/a self.assertEqual(re.compile(pattern, re.S).findall(b'xyz'),
1600n/a [b'xyz'], msg=pattern)
1601n/a
1602n/a def test_match_repr(self):
1603n/a for string in '[abracadabra]', S('[abracadabra]'):
1604n/a m = re.search(r'(.+)(.*?)\1', string)
1605n/a self.assertEqual(repr(m), "<%s.%s object; "
1606n/a "span=(1, 12), match='abracadabra'>" %
1607n/a (type(m).__module__, type(m).__qualname__))
1608n/a for string in (b'[abracadabra]', B(b'[abracadabra]'),
1609n/a bytearray(b'[abracadabra]'),
1610n/a memoryview(b'[abracadabra]')):
1611n/a m = re.search(br'(.+)(.*?)\1', string)
1612n/a self.assertEqual(repr(m), "<%s.%s object; "
1613n/a "span=(1, 12), match=b'abracadabra'>" %
1614n/a (type(m).__module__, type(m).__qualname__))
1615n/a
1616n/a first, second = list(re.finditer("(aa)|(bb)", "aa bb"))
1617n/a self.assertEqual(repr(first), "<%s.%s object; "
1618n/a "span=(0, 2), match='aa'>" %
1619n/a (type(second).__module__, type(first).__qualname__))
1620n/a self.assertEqual(repr(second), "<%s.%s object; "
1621n/a "span=(3, 5), match='bb'>" %
1622n/a (type(second).__module__, type(second).__qualname__))
1623n/a
1624n/a
1625n/a def test_bug_2537(self):
1626n/a # issue 2537: empty submatches
1627n/a for outer_op in ('{0,}', '*', '+', '{1,187}'):
1628n/a for inner_op in ('{0,}', '*', '?'):
1629n/a r = re.compile("^((x|y)%s)%s" % (inner_op, outer_op))
1630n/a m = r.match("xyyzy")
1631n/a self.assertEqual(m.group(0), "xyy")
1632n/a self.assertEqual(m.group(1), "")
1633n/a self.assertEqual(m.group(2), "y")
1634n/a
1635n/a def test_debug_flag(self):
1636n/a pat = r'(\.)(?:[ch]|py)(?(1)$|: )'
1637n/a with captured_stdout() as out:
1638n/a re.compile(pat, re.DEBUG)
1639n/a dump = '''\
1640n/aSUBPATTERN 1 0 0
1641n/a LITERAL 46
1642n/aSUBPATTERN None 0 0
1643n/a BRANCH
1644n/a IN
1645n/a LITERAL 99
1646n/a LITERAL 104
1647n/a OR
1648n/a LITERAL 112
1649n/a LITERAL 121
1650n/aSUBPATTERN None 0 0
1651n/a GROUPREF_EXISTS 1
1652n/a AT AT_END
1653n/a ELSE
1654n/a LITERAL 58
1655n/a LITERAL 32
1656n/a'''
1657n/a self.assertEqual(out.getvalue(), dump)
1658n/a # Debug output is output again even a second time (bypassing
1659n/a # the cache -- issue #20426).
1660n/a with captured_stdout() as out:
1661n/a re.compile(pat, re.DEBUG)
1662n/a self.assertEqual(out.getvalue(), dump)
1663n/a
1664n/a def test_keyword_parameters(self):
1665n/a # Issue #20283: Accepting the string keyword parameter.
1666n/a pat = re.compile(r'(ab)')
1667n/a self.assertEqual(
1668n/a pat.match(string='abracadabra', pos=7, endpos=10).span(), (7, 9))
1669n/a self.assertEqual(
1670n/a pat.fullmatch(string='abracadabra', pos=7, endpos=9).span(), (7, 9))
1671n/a self.assertEqual(
1672n/a pat.search(string='abracadabra', pos=3, endpos=10).span(), (7, 9))
1673n/a self.assertEqual(
1674n/a pat.findall(string='abracadabra', pos=3, endpos=10), ['ab'])
1675n/a self.assertEqual(
1676n/a pat.split(string='abracadabra', maxsplit=1),
1677n/a ['', 'ab', 'racadabra'])
1678n/a self.assertEqual(
1679n/a pat.scanner(string='abracadabra', pos=3, endpos=10).search().span(),
1680n/a (7, 9))
1681n/a
1682n/a def test_bug_20998(self):
1683n/a # Issue #20998: Fullmatch of repeated single character pattern
1684n/a # with ignore case.
1685n/a self.assertEqual(re.fullmatch('[a-c]+', 'ABC', re.I).span(), (0, 3))
1686n/a
1687n/a def test_locale_caching(self):
1688n/a # Issue #22410
1689n/a oldlocale = locale.setlocale(locale.LC_CTYPE)
1690n/a self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
1691n/a for loc in 'en_US.iso88591', 'en_US.utf8':
1692n/a try:
1693n/a locale.setlocale(locale.LC_CTYPE, loc)
1694n/a except locale.Error:
1695n/a # Unsupported locale on this system
1696n/a self.skipTest('test needs %s locale' % loc)
1697n/a
1698n/a re.purge()
1699n/a self.check_en_US_iso88591()
1700n/a self.check_en_US_utf8()
1701n/a re.purge()
1702n/a self.check_en_US_utf8()
1703n/a self.check_en_US_iso88591()
1704n/a
1705n/a def check_en_US_iso88591(self):
1706n/a locale.setlocale(locale.LC_CTYPE, 'en_US.iso88591')
1707n/a self.assertTrue(re.match(b'\xc5\xe5', b'\xc5\xe5', re.L|re.I))
1708n/a self.assertTrue(re.match(b'\xc5', b'\xe5', re.L|re.I))
1709n/a self.assertTrue(re.match(b'\xe5', b'\xc5', re.L|re.I))
1710n/a self.assertTrue(re.match(b'(?Li)\xc5\xe5', b'\xc5\xe5'))
1711n/a self.assertTrue(re.match(b'(?Li)\xc5', b'\xe5'))
1712n/a self.assertTrue(re.match(b'(?Li)\xe5', b'\xc5'))
1713n/a
1714n/a def check_en_US_utf8(self):
1715n/a locale.setlocale(locale.LC_CTYPE, 'en_US.utf8')
1716n/a self.assertTrue(re.match(b'\xc5\xe5', b'\xc5\xe5', re.L|re.I))
1717n/a self.assertIsNone(re.match(b'\xc5', b'\xe5', re.L|re.I))
1718n/a self.assertIsNone(re.match(b'\xe5', b'\xc5', re.L|re.I))
1719n/a self.assertTrue(re.match(b'(?Li)\xc5\xe5', b'\xc5\xe5'))
1720n/a self.assertIsNone(re.match(b'(?Li)\xc5', b'\xe5'))
1721n/a self.assertIsNone(re.match(b'(?Li)\xe5', b'\xc5'))
1722n/a
1723n/a def test_error(self):
1724n/a with self.assertRaises(re.error) as cm:
1725n/a re.compile('(\u20ac))')
1726n/a err = cm.exception
1727n/a self.assertIsInstance(err.pattern, str)
1728n/a self.assertEqual(err.pattern, '(\u20ac))')
1729n/a self.assertEqual(err.pos, 3)
1730n/a self.assertEqual(err.lineno, 1)
1731n/a self.assertEqual(err.colno, 4)
1732n/a self.assertIn(err.msg, str(err))
1733n/a self.assertIn(' at position 3', str(err))
1734n/a self.assertNotIn(' at position 3', err.msg)
1735n/a # Bytes pattern
1736n/a with self.assertRaises(re.error) as cm:
1737n/a re.compile(b'(\xa4))')
1738n/a err = cm.exception
1739n/a self.assertIsInstance(err.pattern, bytes)
1740n/a self.assertEqual(err.pattern, b'(\xa4))')
1741n/a self.assertEqual(err.pos, 3)
1742n/a # Multiline pattern
1743n/a with self.assertRaises(re.error) as cm:
1744n/a re.compile("""
1745n/a (
1746n/a abc
1747n/a )
1748n/a )
1749n/a (
1750n/a """, re.VERBOSE)
1751n/a err = cm.exception
1752n/a self.assertEqual(err.pos, 77)
1753n/a self.assertEqual(err.lineno, 5)
1754n/a self.assertEqual(err.colno, 17)
1755n/a self.assertIn(err.msg, str(err))
1756n/a self.assertIn(' at position 77', str(err))
1757n/a self.assertIn('(line 5, column 17)', str(err))
1758n/a
1759n/a def test_misc_errors(self):
1760n/a self.checkPatternError(r'(', 'missing ), unterminated subpattern', 0)
1761n/a self.checkPatternError(r'((a|b)', 'missing ), unterminated subpattern', 0)
1762n/a self.checkPatternError(r'(a|b))', 'unbalanced parenthesis', 5)
1763n/a self.checkPatternError(r'(?P', 'unexpected end of pattern', 3)
1764n/a self.checkPatternError(r'(?z)', 'unknown extension ?z', 1)
1765n/a self.checkPatternError(r'(?iz)', 'unknown flag', 3)
1766n/a self.checkPatternError(r'(?i', 'missing -, : or )', 3)
1767n/a self.checkPatternError(r'(?#abc', 'missing ), unterminated comment', 0)
1768n/a self.checkPatternError(r'(?<', 'unexpected end of pattern', 3)
1769n/a self.checkPatternError(r'(?<>)', 'unknown extension ?<>', 1)
1770n/a self.checkPatternError(r'(?', 'unexpected end of pattern', 2)
1771n/a
1772n/a def test_enum(self):
1773n/a # Issue #28082: Check that str(flag) returns a human readable string
1774n/a # instead of an integer
1775n/a self.assertIn('ASCII', str(re.A))
1776n/a self.assertIn('DOTALL', str(re.S))
1777n/a
1778n/a def test_pattern_compare(self):
1779n/a pattern1 = re.compile('abc', re.IGNORECASE)
1780n/a
1781n/a # equal to itself
1782n/a self.assertEqual(pattern1, pattern1)
1783n/a self.assertFalse(pattern1 != pattern1)
1784n/a
1785n/a # equal
1786n/a re.purge()
1787n/a pattern2 = re.compile('abc', re.IGNORECASE)
1788n/a self.assertEqual(hash(pattern2), hash(pattern1))
1789n/a self.assertEqual(pattern2, pattern1)
1790n/a
1791n/a # not equal: different pattern
1792n/a re.purge()
1793n/a pattern3 = re.compile('XYZ', re.IGNORECASE)
1794n/a # Don't test hash(pattern3) != hash(pattern1) because there is no
1795n/a # warranty that hash values are different
1796n/a self.assertNotEqual(pattern3, pattern1)
1797n/a
1798n/a # not equal: different flag (flags=0)
1799n/a re.purge()
1800n/a pattern4 = re.compile('abc')
1801n/a self.assertNotEqual(pattern4, pattern1)
1802n/a
1803n/a # only == and != comparison operators are supported
1804n/a with self.assertRaises(TypeError):
1805n/a pattern1 < pattern2
1806n/a
1807n/a def test_pattern_compare_bytes(self):
1808n/a pattern1 = re.compile(b'abc')
1809n/a
1810n/a # equal: test bytes patterns
1811n/a re.purge()
1812n/a pattern2 = re.compile(b'abc')
1813n/a self.assertEqual(hash(pattern2), hash(pattern1))
1814n/a self.assertEqual(pattern2, pattern1)
1815n/a
1816n/a # not equal: pattern of a different types (str vs bytes),
1817n/a # comparison must not raise a BytesWarning
1818n/a re.purge()
1819n/a pattern3 = re.compile('abc')
1820n/a with warnings.catch_warnings():
1821n/a warnings.simplefilter('error', BytesWarning)
1822n/a self.assertNotEqual(pattern3, pattern1)
1823n/a
1824n/a def test_bug_29444(self):
1825n/a s = bytearray(b'abcdefgh')
1826n/a m = re.search(b'[a-h]+', s)
1827n/a m2 = re.search(b'[e-h]+', s)
1828n/a self.assertEqual(m.group(), b'abcdefgh')
1829n/a self.assertEqual(m2.group(), b'efgh')
1830n/a s[:] = b'xyz'
1831n/a self.assertEqual(m.group(), b'xyz')
1832n/a self.assertEqual(m2.group(), b'')
1833n/a
1834n/a
1835n/aclass PatternReprTests(unittest.TestCase):
1836n/a def check(self, pattern, expected):
1837n/a self.assertEqual(repr(re.compile(pattern)), expected)
1838n/a
1839n/a def check_flags(self, pattern, flags, expected):
1840n/a self.assertEqual(repr(re.compile(pattern, flags)), expected)
1841n/a
1842n/a def test_without_flags(self):
1843n/a self.check('random pattern',
1844n/a "re.compile('random pattern')")
1845n/a
1846n/a def test_single_flag(self):
1847n/a self.check_flags('random pattern', re.IGNORECASE,
1848n/a "re.compile('random pattern', re.IGNORECASE)")
1849n/a
1850n/a def test_multiple_flags(self):
1851n/a self.check_flags('random pattern', re.I|re.S|re.X,
1852n/a "re.compile('random pattern', "
1853n/a "re.IGNORECASE|re.DOTALL|re.VERBOSE)")
1854n/a
1855n/a def test_unicode_flag(self):
1856n/a self.check_flags('random pattern', re.U,
1857n/a "re.compile('random pattern')")
1858n/a self.check_flags('random pattern', re.I|re.S|re.U,
1859n/a "re.compile('random pattern', "
1860n/a "re.IGNORECASE|re.DOTALL)")
1861n/a
1862n/a def test_inline_flags(self):
1863n/a self.check('(?i)pattern',
1864n/a "re.compile('(?i)pattern', re.IGNORECASE)")
1865n/a
1866n/a def test_unknown_flags(self):
1867n/a self.check_flags('random pattern', 0x123000,
1868n/a "re.compile('random pattern', 0x123000)")
1869n/a self.check_flags('random pattern', 0x123000|re.I,
1870n/a "re.compile('random pattern', re.IGNORECASE|0x123000)")
1871n/a
1872n/a def test_bytes(self):
1873n/a self.check(b'bytes pattern',
1874n/a "re.compile(b'bytes pattern')")
1875n/a self.check_flags(b'bytes pattern', re.A,
1876n/a "re.compile(b'bytes pattern', re.ASCII)")
1877n/a
1878n/a def test_locale(self):
1879n/a self.check_flags(b'bytes pattern', re.L,
1880n/a "re.compile(b'bytes pattern', re.LOCALE)")
1881n/a
1882n/a def test_quotes(self):
1883n/a self.check('random "double quoted" pattern',
1884n/a '''re.compile('random "double quoted" pattern')''')
1885n/a self.check("random 'single quoted' pattern",
1886n/a '''re.compile("random 'single quoted' pattern")''')
1887n/a self.check('''both 'single' and "double" quotes''',
1888n/a '''re.compile('both \\'single\\' and "double" quotes')''')
1889n/a
1890n/a def test_long_pattern(self):
1891n/a pattern = 'Very %spattern' % ('long ' * 1000)
1892n/a r = repr(re.compile(pattern))
1893n/a self.assertLess(len(r), 300)
1894n/a self.assertEqual(r[:30], "re.compile('Very long long lon")
1895n/a r = repr(re.compile(pattern, re.I))
1896n/a self.assertLess(len(r), 300)
1897n/a self.assertEqual(r[:30], "re.compile('Very long long lon")
1898n/a self.assertEqual(r[-16:], ", re.IGNORECASE)")
1899n/a
1900n/a
1901n/aclass ImplementationTest(unittest.TestCase):
1902n/a """
1903n/a Test implementation details of the re module.
1904n/a """
1905n/a
1906n/a def test_overlap_table(self):
1907n/a f = sre_compile._generate_overlap_table
1908n/a self.assertEqual(f(""), [])
1909n/a self.assertEqual(f("a"), [0])
1910n/a self.assertEqual(f("abcd"), [0, 0, 0, 0])
1911n/a self.assertEqual(f("aaaa"), [0, 1, 2, 3])
1912n/a self.assertEqual(f("ababba"), [0, 0, 1, 2, 0, 1])
1913n/a self.assertEqual(f("abcabdac"), [0, 0, 0, 1, 2, 0, 1, 0])
1914n/a
1915n/a
1916n/aclass ExternalTests(unittest.TestCase):
1917n/a
1918n/a def test_re_benchmarks(self):
1919n/a 're_tests benchmarks'
1920n/a from test.re_tests import benchmarks
1921n/a for pattern, s in benchmarks:
1922n/a with self.subTest(pattern=pattern, string=s):
1923n/a p = re.compile(pattern)
1924n/a self.assertTrue(p.search(s))
1925n/a self.assertTrue(p.match(s))
1926n/a self.assertTrue(p.fullmatch(s))
1927n/a s2 = ' '*10000 + s + ' '*10000
1928n/a self.assertTrue(p.search(s2))
1929n/a self.assertTrue(p.match(s2, 10000))
1930n/a self.assertTrue(p.match(s2, 10000, 10000 + len(s)))
1931n/a self.assertTrue(p.fullmatch(s2, 10000, 10000 + len(s)))
1932n/a
1933n/a def test_re_tests(self):
1934n/a 're_tests test suite'
1935n/a from test.re_tests import tests, SUCCEED, FAIL, SYNTAX_ERROR
1936n/a for t in tests:
1937n/a pattern = s = outcome = repl = expected = None
1938n/a if len(t) == 5:
1939n/a pattern, s, outcome, repl, expected = t
1940n/a elif len(t) == 3:
1941n/a pattern, s, outcome = t
1942n/a else:
1943n/a raise ValueError('Test tuples should have 3 or 5 fields', t)
1944n/a
1945n/a with self.subTest(pattern=pattern, string=s):
1946n/a if outcome == SYNTAX_ERROR: # Expected a syntax error
1947n/a with self.assertRaises(re.error):
1948n/a re.compile(pattern)
1949n/a continue
1950n/a
1951n/a obj = re.compile(pattern)
1952n/a result = obj.search(s)
1953n/a if outcome == FAIL:
1954n/a self.assertIsNone(result, 'Succeeded incorrectly')
1955n/a continue
1956n/a
1957n/a with self.subTest():
1958n/a self.assertTrue(result, 'Failed incorrectly')
1959n/a # Matched, as expected, so now we compute the
1960n/a # result string and compare it to our expected result.
1961n/a start, end = result.span(0)
1962n/a vardict = {'found': result.group(0),
1963n/a 'groups': result.group(),
1964n/a 'flags': result.re.flags}
1965n/a for i in range(1, 100):
1966n/a try:
1967n/a gi = result.group(i)
1968n/a # Special hack because else the string concat fails:
1969n/a if gi is None:
1970n/a gi = "None"
1971n/a except IndexError:
1972n/a gi = "Error"
1973n/a vardict['g%d' % i] = gi
1974n/a for i in result.re.groupindex.keys():
1975n/a try:
1976n/a gi = result.group(i)
1977n/a if gi is None:
1978n/a gi = "None"
1979n/a except IndexError:
1980n/a gi = "Error"
1981n/a vardict[i] = gi
1982n/a self.assertEqual(eval(repl, vardict), expected,
1983n/a 'grouping error')
1984n/a
1985n/a # Try the match with both pattern and string converted to
1986n/a # bytes, and check that it still succeeds.
1987n/a try:
1988n/a bpat = bytes(pattern, "ascii")
1989n/a bs = bytes(s, "ascii")
1990n/a except UnicodeEncodeError:
1991n/a # skip non-ascii tests
1992n/a pass
1993n/a else:
1994n/a with self.subTest('bytes pattern match'):
1995n/a obj = re.compile(bpat)
1996n/a self.assertTrue(obj.search(bs))
1997n/a
1998n/a # Try the match with LOCALE enabled, and check that it
1999n/a # still succeeds.
2000n/a with self.subTest('locale-sensitive match'):
2001n/a obj = re.compile(bpat, re.LOCALE)
2002n/a result = obj.search(bs)
2003n/a if result is None:
2004n/a print('=== Fails on locale-sensitive match', t)
2005n/a
2006n/a # Try the match with the search area limited to the extent
2007n/a # of the match and see if it still succeeds. \B will
2008n/a # break (because it won't match at the end or start of a
2009n/a # string), so we'll ignore patterns that feature it.
2010n/a if (pattern[:2] != r'\B' and pattern[-2:] != r'\B'
2011n/a and result is not None):
2012n/a with self.subTest('range-limited match'):
2013n/a obj = re.compile(pattern)
2014n/a self.assertTrue(obj.search(s, start, end + 1))
2015n/a
2016n/a # Try the match with IGNORECASE enabled, and check that it
2017n/a # still succeeds.
2018n/a with self.subTest('case-insensitive match'):
2019n/a obj = re.compile(pattern, re.IGNORECASE)
2020n/a self.assertTrue(obj.search(s))
2021n/a
2022n/a # Try the match with UNICODE locale enabled, and check
2023n/a # that it still succeeds.
2024n/a with self.subTest('unicode-sensitive match'):
2025n/a obj = re.compile(pattern, re.UNICODE)
2026n/a self.assertTrue(obj.search(s))
2027n/a
2028n/a
2029n/aif __name__ == "__main__":
2030n/a unittest.main()