Debian Codegraph @

PKG-INFO

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