Debian Codegraph @

README.rst

raw
1 Introduction
2 ------------
3
4 This regex implementation is backwards-compatible with the standard 're' module, but offers additional functionality.
5
6 Python 2
7 --------
8
9 Python 2 is no longer supported. The last release that supported Python 2 was 2021.11.10.
10
11 PyPy
12 ----
13
14 This module is targeted at CPython. It expects that all codepoints are the same width, so it won't behave properly with PyPy outside U+0000..U+007F because PyPy stores strings as UTF-8.
15
16 Multithreading
17 --------------
18
19 The regex module releases the GIL during matching on instances of the built-in (immutable) string classes, enabling other Python threads to run concurrently. It is also possible to force the regex module to release the GIL during matching by calling the matching methods with the keyword argument ``concurrent=True``. The behaviour is undefined if the string changes during matching, so use it *only* when it is guaranteed that that won't happen.
20
21 Unicode
22 -------
23
24 This module supports Unicode 16.0.0. Full Unicode case-folding is supported.
25
26 Flags
27 -----
28
29 There are 2 kinds of flag: scoped and global. Scoped flags can apply to only part of a pattern and can be turned on or off; global flags apply to the entire pattern and can only be turned on.
30
31 The scoped flags are: ``ASCII (?a)``, ``FULLCASE (?f)``, ``IGNORECASE (?i)``, ``LOCALE (?L)``, ``MULTILINE (?m)``, ``DOTALL (?s)``, ``UNICODE (?u)``, ``VERBOSE (?x)``, ``WORD (?w)``.
32
33 The global flags are: ``BESTMATCH (?b)``, ``ENHANCEMATCH (?e)``, ``POSIX (?p)``, ``REVERSE (?r)``, ``VERSION0 (?V0)``, ``VERSION1 (?V1)``.
34
35 If neither the ``ASCII``, ``LOCALE`` nor ``UNICODE`` flag is specified, it will default to ``UNICODE`` if the regex pattern is a Unicode string and ``ASCII`` if it's a bytestring.
36
37 The ``ENHANCEMATCH`` flag makes fuzzy matching attempt to improve the fit of the next match that it finds.
38
39 The ``BESTMATCH`` flag makes fuzzy matching search for the best match instead of the next match.
40
41 Old vs new behaviour
42 --------------------
43
44 In order to be compatible with the re module, this module has 2 behaviours:
45
46 * **Version 0** behaviour (old behaviour, compatible with the re module):
47
48 Please note that the re module's behaviour may change over time, and I'll endeavour to match that behaviour in version 0.
49
50 * Indicated by the ``VERSION0`` flag.
51
52 * Zero-width matches are not handled correctly in the re module before Python 3.7. The behaviour in those earlier versions is:
53
54 * ``.split`` won't split a string at a zero-width match.
55
56 * ``.sub`` will advance by one character after a zero-width match.
57
58 * Inline flags apply to the entire pattern, and they can't be turned off.
59
60 * Only simple sets are supported.
61
62 * Case-insensitive matches in Unicode use simple case-folding by default.
63
64 * **Version 1** behaviour (new behaviour, possibly different from the re module):
65
66 * Indicated by the ``VERSION1`` flag.
67
68 * Zero-width matches are handled correctly.
69
70 * Inline flags apply to the end of the group or pattern, and they can be turned off.
71
72 * Nested sets and set operations are supported.
73
74 * Case-insensitive matches in Unicode use full case-folding by default.
75
76 If no version is specified, the regex module will default to ``regex.DEFAULT_VERSION``.
77
78 Case-insensitive matches in Unicode
79 -----------------------------------
80
81 The regex module supports both simple and full case-folding for case-insensitive matches in Unicode. Use of full case-folding can be turned on using the ``FULLCASE`` flag. Please note that this flag affects how the ``IGNORECASE`` flag works; the ``FULLCASE`` flag itself does not turn on case-insensitive matching.
82
83 Version 0 behaviour: the flag is off by default.
84
85 Version 1 behaviour: the flag is on by default.
86
87 Nested sets and set operations
88 ------------------------------
89
90 It's not possible to support both simple sets, as used in the re module, and nested sets at the same time because of a difference in the meaning of an unescaped ``"["`` in a set.
91
92 For example, the pattern ``[[a-z]--[aeiou]]`` is treated in the version 0 behaviour (simple sets, compatible with the re module) as:
93
94 * Set containing "[" and the letters "a" to "z"
95
96 * Literal "--"
97
98 * Set containing letters "a", "e", "i", "o", "u"
99
100 * Literal "]"
101
102 but in the version 1 behaviour (nested sets, enhanced behaviour) as:
103
104 * Set which is:
105
106 * Set containing the letters "a" to "z"
107
108 * but excluding:
109
110 * Set containing the letters "a", "e", "i", "o", "u"
111
112 Version 0 behaviour: only simple sets are supported.
113
114 Version 1 behaviour: nested sets and set operations are supported.
115
116 Notes on named groups
117 ---------------------
118
119 All groups have a group number, starting from 1.
120
121 Groups with the same group name will have the same group number, and groups with a different group name will have a different group number.
122
123 The same name can be used by more than one group, with later captures 'overwriting' earlier captures. All the captures of the group will be available from the ``captures`` method of the match object.
124
125 Group numbers will be reused across different branches of a branch reset, eg. ``(?|(first)|(second))`` has only group 1. If groups have different group names then they will, of course, have different group numbers, eg. ``(?|(?P<foo>first)|(?P<bar>second))`` has group 1 ("foo") and group 2 ("bar").
126
127 In the regex ``(\s+)(?|(?P<foo>[A-Z]+)|(\w+) (?P<foo>[0-9]+)`` there are 2 groups:
128
129 * ``(\s+)`` is group 1.
130
131 * ``(?P<foo>[A-Z]+)`` is group 2, also called "foo".
132
133 * ``(\w+)`` is group 2 because of the branch reset.
134
135 * ``(?P<foo>[0-9]+)`` is group 2 because it's called "foo".
136
137 If you want to prevent ``(\w+)`` from being group 2, you need to name it (different name, different group number).
138
139 Additional features
140 -------------------
141
142 The issue numbers relate to the Python bug tracker, except where listed otherwise.
143
144 Added ``\p{Horiz_Space}`` and ``\p{Vert_Space}`` (`GitHub issue 477 <https://github.com/mrabarnett/mrab-regex/issues/477#issuecomment-1216779547>`_)
145 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
146
147 ``\p{Horiz_Space}`` or ``\p{H}`` matches horizontal whitespace and ``\p{Vert_Space}`` or ``\p{V}`` matches vertical whitespace.
148
149 Added support for lookaround in conditional pattern (`Hg issue 163 <https://github.com/mrabarnett/mrab-regex/issues/163>`_)
150 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
151
152 The test of a conditional pattern can be a lookaround.
153
154 .. sourcecode:: python
155
156 >>> regex.match(r'(?(?=\d)\d+|\w+)', '123abc')
157 <regex.Match object; span=(0, 3), match='123'>
158 >>> regex.match(r'(?(?=\d)\d+|\w+)', 'abc123')
159 <regex.Match object; span=(0, 6), match='abc123'>
160
161 This is not quite the same as putting a lookaround in the first branch of a pair of alternatives.
162
163 .. sourcecode:: python
164
165 >>> print(regex.match(r'(?:(?=\d)\d+\b|\w+)', '123abc'))
166 <regex.Match object; span=(0, 6), match='123abc'>
167 >>> print(regex.match(r'(?(?=\d)\d+\b|\w+)', '123abc'))
168 None
169
170 In the first example, the lookaround matched, but the remainder of the first branch failed to match, and so the second branch was attempted, whereas in the second example, the lookaround matched, and the first branch failed to match, but the second branch was **not** attempted.
171
172 Added POSIX matching (leftmost longest) (`Hg issue 150 <https://github.com/mrabarnett/mrab-regex/issues/150>`_)
173 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
174
175 The POSIX standard for regex is to return the leftmost longest match. This can be turned on using the ``POSIX`` flag.
176
177 .. sourcecode:: python
178
179 >>> # Normal matching.
180 >>> regex.search(r'Mr|Mrs', 'Mrs')
181 <regex.Match object; span=(0, 2), match='Mr'>
182 >>> regex.search(r'one(self)?(selfsufficient)?', 'oneselfsufficient')
183 <regex.Match object; span=(0, 7), match='oneself'>
184 >>> # POSIX matching.
185 >>> regex.search(r'(?p)Mr|Mrs', 'Mrs')
186 <regex.Match object; span=(0, 3), match='Mrs'>
187 >>> regex.search(r'(?p)one(self)?(selfsufficient)?', 'oneselfsufficient')
188 <regex.Match object; span=(0, 17), match='oneselfsufficient'>
189
190 Note that it will take longer to find matches because when it finds a match at a certain position, it won't return that immediately, but will keep looking to see if there's another longer match there.
191
192 Added ``(?(DEFINE)...)`` (`Hg issue 152 <https://github.com/mrabarnett/mrab-regex/issues/152>`_)
193 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
194
195 If there's no group called "DEFINE", then ... will be ignored except that any groups defined within it can be called and that the normal rules for numbering groups still apply.
196
197 .. sourcecode:: python
198
199 >>> regex.search(r'(?(DEFINE)(?P<quant>\d+)(?P<item>\w+))(?&quant) (?&item)', '5 elephants')
200 <regex.Match object; span=(0, 11), match='5 elephants'>
201
202 Added ``(*PRUNE)``, ``(*SKIP)`` and ``(*FAIL)`` (`Hg issue 153 <https://github.com/mrabarnett/mrab-regex/issues/153>`_)
203 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
204
205 ``(*PRUNE)`` discards the backtracking info up to that point. When used in an atomic group or a lookaround, it won't affect the enclosing pattern.
206
207 ``(*SKIP)`` is similar to ``(*PRUNE)``, except that it also sets where in the text the next attempt to match will start. When used in an atomic group or a lookaround, it won't affect the enclosing pattern.
208
209 ``(*FAIL)`` causes immediate backtracking. ``(*F)`` is a permitted abbreviation.
210
211 Added ``\K`` (`Hg issue 151 <https://github.com/mrabarnett/mrab-regex/issues/151>`_)
212 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
213
214 Keeps the part of the entire match after the position where ``\K`` occurred; the part before it is discarded.
215
216 It does not affect what groups return.
217
218 .. sourcecode:: python
219
220 >>> m = regex.search(r'(\w\w\K\w\w\w)', 'abcdef')
221 >>> m[0]
222 'cde'
223 >>> m[1]
224 'abcde'
225 >>>
226 >>> m = regex.search(r'(?r)(\w\w\K\w\w\w)', 'abcdef')
227 >>> m[0]
228 'bc'
229 >>> m[1]
230 'bcdef'
231
232 Added capture subscripting for ``expandf`` and ``subf``/``subfn`` (`Hg issue 133 <https://github.com/mrabarnett/mrab-regex/issues/133>`_)
233 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
234
235 You can use subscripting to get the captures of a repeated group.
236
237 .. sourcecode:: python
238
239 >>> m = regex.match(r"(\w)+", "abc")
240 >>> m.expandf("{1}")
241 'c'
242 >>> m.expandf("{1[0]} {1[1]} {1[2]}")
243 'a b c'
244 >>> m.expandf("{1[-1]} {1[-2]} {1[-3]}")
245 'c b a'
246 >>>
247 >>> m = regex.match(r"(?P<letter>\w)+", "abc")
248 >>> m.expandf("{letter}")
249 'c'
250 >>> m.expandf("{letter[0]} {letter[1]} {letter[2]}")
251 'a b c'
252 >>> m.expandf("{letter[-1]} {letter[-2]} {letter[-3]}")
253 'c b a'
254
255 Added support for referring to a group by number using ``(?P=...)``
256 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
257
258 This is in addition to the existing ``\g<...>``.
259
260 Fixed the handling of locale-sensitive regexes
261 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
262
263 The ``LOCALE`` flag is intended for legacy code and has limited support. You're still recommended to use Unicode instead.
264
265 Added partial matches (`Hg issue 102 <https://github.com/mrabarnett/mrab-regex/issues/102>`_)
266 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
267
268 A partial match is one that matches up to the end of string, but that string has been truncated and you want to know whether a complete match could be possible if the string had not been truncated.
269
270 Partial matches are supported by ``match``, ``search``, ``fullmatch`` and ``finditer`` with the ``partial`` keyword argument.
271
272 Match objects have a ``partial`` attribute, which is ``True`` if it's a partial match.
273
274 For example, if you wanted a user to enter a 4-digit number and check it character by character as it was being entered:
275
276 .. sourcecode:: python
277
278 >>> pattern = regex.compile(r'\d{4}')
279
280 >>> # Initially, nothing has been entered:
281 >>> print(pattern.fullmatch('', partial=True))
282 <regex.Match object; span=(0, 0), match='', partial=True>
283
284 >>> # An empty string is OK, but it's only a partial match.
285 >>> # The user enters a letter:
286 >>> print(pattern.fullmatch('a', partial=True))
287 None
288 >>> # It'll never match.
289
290 >>> # The user deletes that and enters a digit:
291 >>> print(pattern.fullmatch('1', partial=True))
292 <regex.Match object; span=(0, 1), match='1', partial=True>
293 >>> # It matches this far, but it's only a partial match.
294
295 >>> # The user enters 2 more digits:
296 >>> print(pattern.fullmatch('123', partial=True))
297 <regex.Match object; span=(0, 3), match='123', partial=True>
298 >>> # It matches this far, but it's only a partial match.
299
300 >>> # The user enters another digit:
301 >>> print(pattern.fullmatch('1234', partial=True))
302 <regex.Match object; span=(0, 4), match='1234'>
303 >>> # It's a complete match.
304
305 >>> # If the user enters another digit:
306 >>> print(pattern.fullmatch('12345', partial=True))
307 None
308 >>> # It's no longer a match.
309
310 >>> # This is a partial match:
311 >>> pattern.match('123', partial=True).partial
312 True
313
314 >>> # This is a complete match:
315 >>> pattern.match('1233', partial=True).partial
316 False
317
318 ``*`` operator not working correctly with sub() (`Hg issue 106 <https://github.com/mrabarnett/mrab-regex/issues/106>`_)
319 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
320
321 Sometimes it's not clear how zero-width matches should be handled. For example, should ``.*`` match 0 characters directly after matching >0 characters?
322
323 .. sourcecode:: python
324
325 >>> regex.sub('.*', 'x', 'test')
326 'xx'
327 >>> regex.sub('.*?', '|', 'test')
328 '|||||||||'
329
330 Added ``capturesdict`` (`Hg issue 86 <https://github.com/mrabarnett/mrab-regex/issues/86>`_)
331 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
332
333 ``capturesdict`` is a combination of ``groupdict`` and ``captures``:
334
335 ``groupdict`` returns a dict of the named groups and the last capture of those groups.
336
337 ``captures`` returns a list of all the captures of a group
338
339 ``capturesdict`` returns a dict of the named groups and lists of all the captures of those groups.
340
341 .. sourcecode:: python
342
343 >>> m = regex.match(r"(?:(?P<word>\w+) (?P<digits>\d+)\n)+", "one 1\ntwo 2\nthree 3\n")
344 >>> m.groupdict()
345 {'word': 'three', 'digits': '3'}
346 >>> m.captures("word")
347 ['one', 'two', 'three']
348 >>> m.captures("digits")
349 ['1', '2', '3']
350 >>> m.capturesdict()
351 {'word': ['one', 'two', 'three'], 'digits': ['1', '2', '3']}
352
353 Added ``allcaptures`` and ``allspans`` (`Git issue 474 <https://github.com/mrabarnett/mrab-regex/issues/474>`_)
354 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
355
356 ``allcaptures`` returns a list of all the captures of all the groups.
357
358 ``allspans`` returns a list of all the spans of the all captures of all the groups.
359
360 .. sourcecode:: python
361
362 >>> m = regex.match(r"(?:(?P<word>\w+) (?P<digits>\d+)\n)+", "one 1\ntwo 2\nthree 3\n")
363 >>> m.allcaptures()
364 (['one 1\ntwo 2\nthree 3\n'], ['one', 'two', 'three'], ['1', '2', '3'])
365 >>> m.allspans()
366 ([(0, 20)], [(0, 3), (6, 9), (12, 17)], [(4, 5), (10, 11), (18, 19)])
367
368 Allow duplicate names of groups (`Hg issue 87 <https://github.com/mrabarnett/mrab-regex/issues/87>`_)
369 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
370
371 Group names can be duplicated.
372
373 .. sourcecode:: python
374
375 >>> # With optional groups:
376 >>>
377 >>> # Both groups capture, the second capture 'overwriting' the first.
378 >>> m = regex.match(r"(?P<item>\w+)? or (?P<item>\w+)?", "first or second")
379 >>> m.group("item")
380 'second'
381 >>> m.captures("item")
382 ['first', 'second']
383 >>> # Only the second group captures.
384 >>> m = regex.match(r"(?P<item>\w+)? or (?P<item>\w+)?", " or second")
385 >>> m.group("item")
386 'second'
387 >>> m.captures("item")
388 ['second']
389 >>> # Only the first group captures.
390 >>> m = regex.match(r"(?P<item>\w+)? or (?P<item>\w+)?", "first or ")
391 >>> m.group("item")
392 'first'
393 >>> m.captures("item")
394 ['first']
395 >>>
396 >>> # With mandatory groups:
397 >>>
398 >>> # Both groups capture, the second capture 'overwriting' the first.
399 >>> m = regex.match(r"(?P<item>\w*) or (?P<item>\w*)?", "first or second")
400 >>> m.group("item")
401 'second'
402 >>> m.captures("item")
403 ['first', 'second']
404 >>> # Again, both groups capture, the second capture 'overwriting' the first.
405 >>> m = regex.match(r"(?P<item>\w*) or (?P<item>\w*)", " or second")
406 >>> m.group("item")
407 'second'
408 >>> m.captures("item")
409 ['', 'second']
410 >>> # And yet again, both groups capture, the second capture 'overwriting' the first.
411 >>> m = regex.match(r"(?P<item>\w*) or (?P<item>\w*)", "first or ")
412 >>> m.group("item")
413 ''
414 >>> m.captures("item")
415 ['first', '']
416
417 Added ``fullmatch`` (`issue #16203 <https://bugs.python.org/issue16203>`_)
418 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
419
420 ``fullmatch`` behaves like ``match``, except that it must match all of the string.
421
422 .. sourcecode:: python
423
424 >>> print(regex.fullmatch(r"abc", "abc").span())
425 (0, 3)
426 >>> print(regex.fullmatch(r"abc", "abcx"))
427 None
428 >>> print(regex.fullmatch(r"abc", "abcx", endpos=3).span())
429 (0, 3)
430 >>> print(regex.fullmatch(r"abc", "xabcy", pos=1, endpos=4).span())
431 (1, 4)
432 >>>
433 >>> regex.match(r"a.*?", "abcd").group(0)
434 'a'
435 >>> regex.fullmatch(r"a.*?", "abcd").group(0)
436 'abcd'
437
438 Added ``subf`` and ``subfn``
439 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
440
441 ``subf`` and ``subfn`` are alternatives to ``sub`` and ``subn`` respectively. When passed a replacement string, they treat it as a format string.
442
443 .. sourcecode:: python
444
445 >>> regex.subf(r"(\w+) (\w+)", "{0} => {2} {1}", "foo bar")
446 'foo bar => bar foo'
447 >>> regex.subf(r"(?P<word1>\w+) (?P<word2>\w+)", "{word2} {word1}", "foo bar")
448 'bar foo'
449
450 Added ``expandf`` to match object
451 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
452
453 ``expandf`` is an alternative to ``expand``. When passed a replacement string, it treats it as a format string.
454
455 .. sourcecode:: python
456
457 >>> m = regex.match(r"(\w+) (\w+)", "foo bar")
458 >>> m.expandf("{0} => {2} {1}")
459 'foo bar => bar foo'
460 >>>
461 >>> m = regex.match(r"(?P<word1>\w+) (?P<word2>\w+)", "foo bar")
462 >>> m.expandf("{word2} {word1}")
463 'bar foo'
464
465 Detach searched string
466 ^^^^^^^^^^^^^^^^^^^^^^
467
468 A match object contains a reference to the string that was searched, via its ``string`` attribute. The ``detach_string`` method will 'detach' that string, making it available for garbage collection, which might save valuable memory if that string is very large.
469
470 .. sourcecode:: python
471
472 >>> m = regex.search(r"\w+", "Hello world")
473 >>> print(m.group())
474 Hello
475 >>> print(m.string)
476 Hello world
477 >>> m.detach_string()
478 >>> print(m.group())
479 Hello
480 >>> print(m.string)
481 None
482
483 Recursive patterns (`Hg issue 27 <https://github.com/mrabarnett/mrab-regex/issues/27>`_)
484 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
485
486 Recursive and repeated patterns are supported.
487
488 ``(?R)`` or ``(?0)`` tries to match the entire regex recursively. ``(?1)``, ``(?2)``, etc, try to match the relevant group.
489
490 ``(?&name)`` tries to match the named group.
491
492 .. sourcecode:: python
493
494 >>> regex.match(r"(Tarzan|Jane) loves (?1)", "Tarzan loves Jane").groups()
495 ('Tarzan',)
496 >>> regex.match(r"(Tarzan|Jane) loves (?1)", "Jane loves Tarzan").groups()
497 ('Jane',)
498
499 >>> m = regex.search(r"(\w)(?:(?R)|(\w?))\1", "kayak")
500 >>> m.group(0, 1, 2)
501 ('kayak', 'k', None)
502
503 The first two examples show how the subpattern within the group is reused, but is _not_ itself a group. In other words, ``"(Tarzan|Jane) loves (?1)"`` is equivalent to ``"(Tarzan|Jane) loves (?:Tarzan|Jane)"``.
504
505 It's possible to backtrack into a recursed or repeated group.
506
507 You can't call a group if there is more than one group with that group name or group number (``"ambiguous group reference"``).
508
509 The alternative forms ``(?P>name)`` and ``(?P&name)`` are also supported.
510
511 Full Unicode case-folding is supported
512 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
513
514 In version 1 behaviour, the regex module uses full case-folding when performing case-insensitive matches in Unicode.
515
516 .. sourcecode:: python
517
518 >>> regex.match(r"(?iV1)strasse", "stra\N{LATIN SMALL LETTER SHARP S}e").span()
519 (0, 6)
520 >>> regex.match(r"(?iV1)stra\N{LATIN SMALL LETTER SHARP S}e", "STRASSE").span()
521 (0, 7)
522
523 In version 0 behaviour, it uses simple case-folding for backward compatibility with the re module.
524
525 Approximate "fuzzy" matching (`Hg issue 12 <https://github.com/mrabarnett/mrab-regex/issues/12>`_, `Hg issue 41 <https://github.com/mrabarnett/mrab-regex/issues/41>`_, `Hg issue 109 <https://github.com/mrabarnett/mrab-regex/issues/109>`_)
526 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
527
528 Regex usually attempts an exact match, but sometimes an approximate, or "fuzzy", match is needed, for those cases where the text being searched may contain errors in the form of inserted, deleted or substituted characters.
529
530 A fuzzy regex specifies which types of errors are permitted, and, optionally, either the minimum and maximum or only the maximum permitted number of each type. (You cannot specify only a minimum.)
531
532 The 3 types of error are:
533
534 * Insertion, indicated by "i"
535
536 * Deletion, indicated by "d"
537
538 * Substitution, indicated by "s"
539
540 In addition, "e" indicates any type of error.
541
542 The fuzziness of a regex item is specified between "{" and "}" after the item.
543
544 Examples:
545
546 * ``foo`` match "foo" exactly
547
548 * ``(?:foo){i}`` match "foo", permitting insertions
549
550 * ``(?:foo){d}`` match "foo", permitting deletions
551
552 * ``(?:foo){s}`` match "foo", permitting substitutions
553
554 * ``(?:foo){i,s}`` match "foo", permitting insertions and substitutions
555
556 * ``(?:foo){e}`` match "foo", permitting errors
557
558 If a certain type of error is specified, then any type not specified will **not** be permitted.
559
560 In the following examples I'll omit the item and write only the fuzziness:
561
562 * ``{d<=3}`` permit at most 3 deletions, but no other types
563
564 * ``{i<=1,s<=2}`` permit at most 1 insertion and at most 2 substitutions, but no deletions
565
566 * ``{1<=e<=3}`` permit at least 1 and at most 3 errors
567
568 * ``{i<=2,d<=2,e<=3}`` permit at most 2 insertions, at most 2 deletions, at most 3 errors in total, but no substitutions
569
570 It's also possible to state the costs of each type of error and the maximum permitted total cost.
571
572 Examples:
573
574 * ``{2i+2d+1s<=4}`` each insertion costs 2, each deletion costs 2, each substitution costs 1, the total cost must not exceed 4
575
576 * ``{i<=1,d<=1,s<=1,2i+2d+1s<=4}`` at most 1 insertion, at most 1 deletion, at most 1 substitution; each insertion costs 2, each deletion costs 2, each substitution costs 1, the total cost must not exceed 4
577
578 You can also use "<" instead of "<=" if you want an exclusive minimum or maximum.
579
580 You can add a test to perform on a character that's substituted or inserted.
581
582 Examples:
583
584 * ``{s<=2:[a-z]}`` at most 2 substitutions, which must be in the character set ``[a-z]``.
585
586 * ``{s<=2,i<=3:\d}`` at most 2 substitutions, at most 3 insertions, which must be digits.
587
588 By default, fuzzy matching searches for the first match that meets the given constraints. The ``ENHANCEMATCH`` flag will cause it to attempt to improve the fit (i.e. reduce the number of errors) of the match that it has found.
589
590 The ``BESTMATCH`` flag will make it search for the best match instead.
591
592 Further examples to note:
593
594 * ``regex.search("(dog){e}", "cat and dog")[1]`` returns ``"cat"`` because that matches ``"dog"`` with 3 errors (an unlimited number of errors is permitted).
595
596 * ``regex.search("(dog){e<=1}", "cat and dog")[1]`` returns ``" dog"`` (with a leading space) because that matches ``"dog"`` with 1 error, which is within the limit.
597
598 * ``regex.search("(?e)(dog){e<=1}", "cat and dog")[1]`` returns ``"dog"`` (without a leading space) because the fuzzy search matches ``" dog"`` with 1 error, which is within the limit, and the ``(?e)`` then it attempts a better fit.
599
600 In the first two examples there are perfect matches later in the string, but in neither case is it the first possible match.
601
602 The match object has an attribute ``fuzzy_counts`` which gives the total number of substitutions, insertions and deletions.
603
604 .. sourcecode:: python
605
606 >>> # A 'raw' fuzzy match:
607 >>> regex.fullmatch(r"(?:cats|cat){e<=1}", "cat").fuzzy_counts
608 (0, 0, 1)
609 >>> # 0 substitutions, 0 insertions, 1 deletion.
610
611 >>> # A better match might be possible if the ENHANCEMATCH flag used:
612 >>> regex.fullmatch(r"(?e)(?:cats|cat){e<=1}", "cat").fuzzy_counts
613 (0, 0, 0)
614 >>> # 0 substitutions, 0 insertions, 0 deletions.
615
616 The match object also has an attribute ``fuzzy_changes`` which gives a tuple of the positions of the substitutions, insertions and deletions.
617
618 .. sourcecode:: python
619
620 >>> m = regex.search('(fuu){i<=2,d<=2,e<=5}', 'anaconda foo bar')
621 >>> m
622 <regex.Match object; span=(7, 10), match='a f', fuzzy_counts=(0, 2, 2)>
623 >>> m.fuzzy_changes
624 ([], [7, 8], [10, 11])
625
626 What this means is that if the matched part of the string had been:
627
628 .. sourcecode:: python
629
630 'anacondfuuoo bar'
631
632 it would've been an exact match.
633
634 However, there were insertions at positions 7 and 8:
635
636 .. sourcecode:: python
637
638 'anaconda fuuoo bar'
639 ^^
640
641 and deletions at positions 10 and 11:
642
643 .. sourcecode:: python
644
645 'anaconda f~~oo bar'
646 ^^
647
648 So the actual string was:
649
650 .. sourcecode:: python
651
652 'anaconda foo bar'
653
654 Named lists ``\L<name>`` (`Hg issue 11 <https://github.com/mrabarnett/mrab-regex/issues/11>`_)
655 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
656
657 There are occasions where you may want to include a list (actually, a set) of options in a regex.
658
659 One way is to build the pattern like this:
660
661 .. sourcecode:: python
662
663 >>> p = regex.compile(r"first|second|third|fourth|fifth")
664
665 but if the list is large, parsing the resulting regex can take considerable time, and care must also be taken that the strings are properly escaped and properly ordered, for example, "cats" before "cat".
666
667 The new alternative is to use a named list:
668
669 .. sourcecode:: python
670
671 >>> option_set = ["first", "second", "third", "fourth", "fifth"]
672 >>> p = regex.compile(r"\L<options>", options=option_set)
673
674 The order of the items is irrelevant, they are treated as a set. The named lists are available as the ``.named_lists`` attribute of the pattern object :
675
676 .. sourcecode:: python
677
678 >>> print(p.named_lists)
679 {'options': frozenset({'third', 'first', 'fifth', 'fourth', 'second'})}
680
681 If there are any unused keyword arguments, ``ValueError`` will be raised unless you tell it otherwise:
682
683 .. sourcecode:: python
684
685 >>> option_set = ["first", "second", "third", "fourth", "fifth"]
686 >>> p = regex.compile(r"\L<options>", options=option_set, other_options=[])
687 Traceback (most recent call last):
688 File "<stdin>", line 1, in <module>
689 File "C:\Python310\lib\site-packages\regex\regex.py", line 353, in compile
690 return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern)
691 File "C:\Python310\lib\site-packages\regex\regex.py", line 500, in _compile
692 complain_unused_args()
693 File "C:\Python310\lib\site-packages\regex\regex.py", line 483, in complain_unused_args
694 raise ValueError('unused keyword argument {!a}'.format(any_one))
695 ValueError: unused keyword argument 'other_options'
696 >>> p = regex.compile(r"\L<options>", options=option_set, other_options=[], ignore_unused=True)
697 >>> p = regex.compile(r"\L<options>", options=option_set, other_options=[], ignore_unused=False)
698 Traceback (most recent call last):
699 File "<stdin>", line 1, in <module>
700 File "C:\Python310\lib\site-packages\regex\regex.py", line 353, in compile
701 return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern)
702 File "C:\Python310\lib\site-packages\regex\regex.py", line 500, in _compile
703 complain_unused_args()
704 File "C:\Python310\lib\site-packages\regex\regex.py", line 483, in complain_unused_args
705 raise ValueError('unused keyword argument {!a}'.format(any_one))
706 ValueError: unused keyword argument 'other_options'
707 >>>
708
709 Start and end of word
710 ^^^^^^^^^^^^^^^^^^^^^
711
712 ``\m`` matches at the start of a word.
713
714 ``\M`` matches at the end of a word.
715
716 Compare with ``\b``, which matches at the start or end of a word.
717
718 Unicode line separators
719 ^^^^^^^^^^^^^^^^^^^^^^^
720
721 Normally the only line separator is ``\n`` (``\x0A``), but if the ``WORD`` flag is turned on then the line separators are ``\x0D\x0A``, ``\x0A``, ``\x0B``, ``\x0C`` and ``\x0D``, plus ``\x85``, ``\u2028`` and ``\u2029`` when working with Unicode.
722
723 This affects the regex dot ``"."``, which, with the ``DOTALL`` flag turned off, matches any character except a line separator. It also affects the line anchors ``^`` and ``$`` (in multiline mode).
724
725 Set operators
726 ^^^^^^^^^^^^^
727
728 **Version 1 behaviour only**
729
730 Set operators have been added, and a set ``[...]`` can include nested sets.
731
732 The operators, in order of increasing precedence, are:
733
734 * ``||`` for union ("x||y" means "x or y")
735
736 * ``~~`` (double tilde) for symmetric difference ("x~~y" means "x or y, but not both")
737
738 * ``&&`` for intersection ("x&&y" means "x and y")
739
740 * ``--`` (double dash) for difference ("x--y" means "x but not y")
741
742 Implicit union, ie, simple juxtaposition like in ``[ab]``, has the highest precedence. Thus, ``[ab&&cd]`` is the same as ``[[a||b]&&[c||d]]``.
743
744 Examples:
745
746 * ``[ab]`` # Set containing 'a' and 'b'
747
748 * ``[a-z]`` # Set containing 'a' .. 'z'
749
750 * ``[[a-z]--[qw]]`` # Set containing 'a' .. 'z', but not 'q' or 'w'
751
752 * ``[a-z--qw]`` # Same as above
753
754 * ``[\p{L}--QW]`` # Set containing all letters except 'Q' and 'W'
755
756 * ``[\p{N}--[0-9]]`` # Set containing all numbers except '0' .. '9'
757
758 * ``[\p{ASCII}&&\p{Letter}]`` # Set containing all characters which are ASCII and letter
759
760 regex.escape (`issue #2650 <https://bugs.python.org/issue2650>`_)
761 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
762
763 regex.escape has an additional keyword parameter ``special_only``. When True, only 'special' regex characters, such as '?', are escaped.
764
765 .. sourcecode:: python
766
767 >>> regex.escape("foo!?", special_only=False)
768 'foo\\!\\?'
769 >>> regex.escape("foo!?", special_only=True)
770 'foo!\\?'
771
772 regex.escape (`Hg issue 249 <https://github.com/mrabarnett/mrab-regex/issues/249>`_)
773 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
774
775 regex.escape has an additional keyword parameter ``literal_spaces``. When True, spaces are not escaped.
776
777 .. sourcecode:: python
778
779 >>> regex.escape("foo bar!?", literal_spaces=False)
780 'foo\\ bar!\\?'
781 >>> regex.escape("foo bar!?", literal_spaces=True)
782 'foo bar!\\?'
783
784 Repeated captures (`issue #7132 <https://bugs.python.org/issue7132>`_)
785 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
786
787 A match object has additional methods which return information on all the successful matches of a repeated group. These methods are:
788
789 * ``matchobject.captures([group1, ...])``
790
791 * Returns a list of the strings matched in a group or groups. Compare with ``matchobject.group([group1, ...])``.
792
793 * ``matchobject.starts([group])``
794
795 * Returns a list of the start positions. Compare with ``matchobject.start([group])``.
796
797 * ``matchobject.ends([group])``
798
799 * Returns a list of the end positions. Compare with ``matchobject.end([group])``.
800
801 * ``matchobject.spans([group])``
802
803 * Returns a list of the spans. Compare with ``matchobject.span([group])``.
804
805 .. sourcecode:: python
806
807 >>> m = regex.search(r"(\w{3})+", "123456789")
808 >>> m.group(1)
809 '789'
810 >>> m.captures(1)
811 ['123', '456', '789']
812 >>> m.start(1)
813 6
814 >>> m.starts(1)
815 [0, 3, 6]
816 >>> m.end(1)
817 9
818 >>> m.ends(1)
819 [3, 6, 9]
820 >>> m.span(1)
821 (6, 9)
822 >>> m.spans(1)
823 [(0, 3), (3, 6), (6, 9)]
824
825 Atomic grouping ``(?>...)`` (`issue #433030 <https://bugs.python.org/issue433030>`_)
826 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
827
828 If the following pattern subsequently fails, then the subpattern as a whole will fail.
829
830 Possessive quantifiers
831 ^^^^^^^^^^^^^^^^^^^^^^
832
833 ``(?:...)?+`` ; ``(?:...)*+`` ; ``(?:...)++`` ; ``(?:...){min,max}+``
834
835 The subpattern is matched up to 'max' times. If the following pattern subsequently fails, then all the repeated subpatterns will fail as a whole. For example, ``(?:...)++`` is equivalent to ``(?>(?:...)+)``.
836
837 Scoped flags (`issue #433028 <https://bugs.python.org/issue433028>`_)
838 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
839
840 ``(?flags-flags:...)``
841
842 The flags will apply only to the subpattern. Flags can be turned on or off.
843
844 Definition of 'word' character (`issue #1693050 <https://bugs.python.org/issue1693050>`_)
845 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
846
847 The definition of a 'word' character has been expanded for Unicode. It conforms to the Unicode specification at ``http://www.unicode.org/reports/tr29/``.
848
849 Variable-length lookbehind
850 ^^^^^^^^^^^^^^^^^^^^^^^^^^
851
852 A lookbehind can match a variable-length string.
853
854 Flags argument for regex.split, regex.sub and regex.subn (`issue #3482 <https://bugs.python.org/issue3482>`_)
855 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
856
857 ``regex.split``, ``regex.sub`` and ``regex.subn`` support a 'flags' argument.
858
859 Pos and endpos arguments for regex.sub and regex.subn
860 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
861
862 ``regex.sub`` and ``regex.subn`` support 'pos' and 'endpos' arguments.
863
864 'Overlapped' argument for regex.findall and regex.finditer
865 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
866
867 ``regex.findall`` and ``regex.finditer`` support an 'overlapped' flag which permits overlapped matches.
868
869 Splititer
870 ^^^^^^^^^
871
872 ``regex.splititer`` has been added. It's a generator equivalent of ``regex.split``.
873
874 Subscripting match objects for groups
875 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
876
877 A match object accepts access to the groups via subscripting and slicing:
878
879 .. sourcecode:: python
880
881 >>> m = regex.search(r"(?P<before>.*?)(?P<num>\d+)(?P<after>.*)", "pqr123stu")
882 >>> print(m["before"])
883 pqr
884 >>> print(len(m))
885 4
886 >>> print(m[:])
887 ('pqr123stu', 'pqr', '123', 'stu')
888
889 Named groups
890 ^^^^^^^^^^^^
891
892 Groups can be named with ``(?<name>...)`` as well as the existing ``(?P<name>...)``.
893
894 Group references
895 ^^^^^^^^^^^^^^^^
896
897 Groups can be referenced within a pattern with ``\g<name>``. This also allows there to be more than 99 groups.
898
899 Named characters ``\N{name}``
900 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
901
902 Named characters are supported. Note that only those known by Python's Unicode database will be recognised.
903
904 Unicode codepoint properties, including scripts and blocks
905 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
906
907 ``\p{property=value}``; ``\P{property=value}``; ``\p{value}`` ; ``\P{value}``
908
909 Many Unicode properties are supported, including blocks and scripts. ``\p{property=value}`` or ``\p{property:value}`` matches a character whose property ``property`` has value ``value``. The inverse of ``\p{property=value}`` is ``\P{property=value}`` or ``\p{^property=value}``.
910
911 If the short form ``\p{value}`` is used, the properties are checked in the order: ``General_Category``, ``Script``, ``Block``, binary property:
912
913 * ``Latin``, the 'Latin' script (``Script=Latin``).
914
915 * ``BasicLatin``, the 'BasicLatin' block (``Block=BasicLatin``).
916
917 * ``Alphabetic``, the 'Alphabetic' binary property (``Alphabetic=Yes``).
918
919 A short form starting with ``Is`` indicates a script or binary property:
920
921 * ``IsLatin``, the 'Latin' script (``Script=Latin``).
922
923 * ``IsAlphabetic``, the 'Alphabetic' binary property (``Alphabetic=Yes``).
924
925 A short form starting with ``In`` indicates a block property:
926
927 * ``InBasicLatin``, the 'BasicLatin' block (``Block=BasicLatin``).
928
929 POSIX character classes
930 ^^^^^^^^^^^^^^^^^^^^^^^
931
932 ``[[:alpha:]]``; ``[[:^alpha:]]``
933
934 POSIX character classes are supported. These are normally treated as an alternative form of ``\p{...}``.
935
936 The exceptions are ``alnum``, ``digit``, ``punct`` and ``xdigit``, whose definitions are different from those of Unicode.
937
938 ``[[:alnum:]]`` is equivalent to ``\p{posix_alnum}``.
939
940 ``[[:digit:]]`` is equivalent to ``\p{posix_digit}``.
941
942 ``[[:punct:]]`` is equivalent to ``\p{posix_punct}``.
943
944 ``[[:xdigit:]]`` is equivalent to ``\p{posix_xdigit}``.
945
946 Search anchor ``\G``
947 ^^^^^^^^^^^^^^^^^^^^
948
949 A search anchor has been added. It matches at the position where each search started/continued and can be used for contiguous matches or in negative variable-length lookbehinds to limit how far back the lookbehind goes:
950
951 .. sourcecode:: python
952
953 >>> regex.findall(r"\w{2}", "abcd ef")
954 ['ab', 'cd', 'ef']
955 >>> regex.findall(r"\G\w{2}", "abcd ef")
956 ['ab', 'cd']
957
958 * The search starts at position 0 and matches 'ab'.
959
960 * The search continues at position 2 and matches 'cd'.
961
962 * The search continues at position 4 and fails to match any letters.
963
964 * The anchor stops the search start position from being advanced, so there are no more results.
965
966 Reverse searching
967 ^^^^^^^^^^^^^^^^^
968
969 Searches can also work backwards:
970
971 .. sourcecode:: python
972
973 >>> regex.findall(r".", "abc")
974 ['a', 'b', 'c']
975 >>> regex.findall(r"(?r).", "abc")
976 ['c', 'b', 'a']
977
978 Note that the result of a reverse search is not necessarily the reverse of a forward search:
979
980 .. sourcecode:: python
981
982 >>> regex.findall(r"..", "abcde")
983 ['ab', 'cd']
984 >>> regex.findall(r"(?r)..", "abcde")
985 ['de', 'bc']
986
987 Matching a single grapheme ``\X``
988 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
989
990 The grapheme matcher is supported. It conforms to the Unicode specification at ``http://www.unicode.org/reports/tr29/``.
991
992 Branch reset ``(?|...|...)``
993 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
994
995 Group numbers will be reused across the alternatives, but groups with different names will have different group numbers.
996
997 .. sourcecode:: python
998
999 >>> regex.match(r"(?|(first)|(second))", "first").groups()
1000 ('first',)
1001 >>> regex.match(r"(?|(first)|(second))", "second").groups()
1002 ('second',)
1003
1004 Note that there is only one group.
1005
1006 Default Unicode word boundary
1007 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1008
1009 The ``WORD`` flag changes the definition of a 'word boundary' to that of a default Unicode word boundary. This applies to ``\b`` and ``\B``.
1010
1011 Timeout
1012 ^^^^^^^
1013
1014 The matching methods and functions support timeouts. The timeout (in seconds) applies to the entire operation:
1015
1016 .. sourcecode:: python
1017
1018 >>> from time import sleep
1019 >>>
1020 >>> def fast_replace(m):
1021 ... return 'X'
1022 ...
1023 >>> def slow_replace(m):
1024 ... sleep(0.5)
1025 ... return 'X'
1026 ...
1027 >>> regex.sub(r'[a-z]', fast_replace, 'abcde', timeout=2)
1028 'XXXXX'
1029 >>> regex.sub(r'[a-z]', slow_replace, 'abcde', timeout=2)
1030 Traceback (most recent call last):
1031 File "<stdin>", line 1, in <module>
1032 File "C:\Python310\lib\site-packages\regex\regex.py", line 278, in sub
1033 return pat.sub(repl, string, count, pos, endpos, concurrent, timeout)
1034 TimeoutError: regex timed out