Project description

Introduction

This new regex implementation is intended eventually to replace Python’s current re module implementation.

For testing and comparison with the current ‘re’ module the new implementation is in the form of a module called ‘regex’.

Also included are the compiled binary .pyd files for Python 2.5-2.7 and Python 3.1-3.4 on 32-bit Windows.

Old vs new behaviour

This module has 2 behaviours:

Version 0 behaviour (old behaviour, compatible with the current re module):

Indicated by the VERSION0 or V0 flag, or (?V0) in the pattern.

.split won’t split a string at a zero-width match.

Inline flags apply to the entire pattern, and they can’t be turned off.

Only simple sets are supported.

Case-insensitive matches in Unicode use simple case-folding by default.

Version 1 behaviour (new behaviour, different from the current re module):

Indicated by the VERSION1 or V1 flag, or (?V1) in the pattern.

.split will split a string at a zero-width match.

Inline flags apply to the end of the group or pattern, and they can be turned off.

Nested sets and set operations are supported.

Case-insensitive matches in Unicode use full case-folding by default.

If no version is specified, the regex module will default to regex.DEFAULT_VERSION. In the short term this will be VERSION0, but in the longer term it will be VERSION1.

Case-insensitive matches in Unicode

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 or F flag, or (?f) in the pattern. Please note that this flag affects how the IGNORECASE flag works; the FULLCASE flag itself does not turn on case-insensitive matching.

In the version 0 behaviour, the flag is off by default.

In the version 1 behaviour, the flag is on by default.

Nested sets and set operations

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.

For example, the pattern [[a-z]--[aeiou]] is treated in the version 0 behaviour (simple sets, compatible with the re module) as:

Set containing “[” and the letters “a” to “z”

Literal “–”

Set containing letters “a”, “e”, “i”, “o”, “u”

but in the version 1 behaviour (nested sets, enhanced behaviour) as:

Set which is:

Set containing the letters “a” to “z”

but excluding:

Set containing the letters “a”, “e”, “i”, “o”, “u”

Version 0 behaviour: only simple sets are supported.

Version 1 behaviour: nested sets and set operations are supported.

Flags

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.

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.

The ENHANCEMATCH flag makes fuzzy matching attempt to improve the fit of the next match that it finds.

The BESTMATCH flag makes fuzzy matching search for the best match instead of the next match.

Notes on named capture groups

All capture groups have a group number, starting from 1.

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.

The same name can be used by more than one group, with later captures ‘overwriting’ earlier captures. All of the captures of the group will be available from the captures method of the match object.

Group numbers will be reused across different branches of a branch reset, eg. (?|(first)|(second)) has only group 1. If capture 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”).

In the regex (\s+)(?|(?P<foo>[A-Z]+)|(\w+)(?<foo>[0-9]+) there are 2 groups:

(\s+) is group 1.

(?P<foo>[A-Z]+) is group 2, also called “foo”.

(\w+) is group 2 because of the branch reset.

(?<foo>[0-9]+) is group 2 because it’s called “foo”.

If you want to prevent (\w+) from being group 2, you need to name it (different name, different group number).

Multithreading

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.

Building for 64-bits

If the source files are built for a 64-bit target then the string positions will also be 64-bit.

Unicode

This module supports Unicode 6.3.

Full Unicode case-folding is supported.

Additional features

The issue numbers relate to the Python bug tracker, except where listed as “Hg issue”.

re.group() should never return a bytearray (issue #18468)

For compatibility with the re module, the regex module returns all matching bytestrings as bytes, starting from Python 3.4.

A match object contains a reference to the string that was searched, via its string attribute. The match object now has a detach_string method that will ‘detach’ that string, making it available for garbage collection (this might save valuable memory if that string is very large).

The first two examples show how the subpattern within the capture group is reused, but is _not_ itself a capture group. In other words, "(Tarzan|Jane) loves (?1)" is equivalent to "(Tarzan|Jane) loves (?:Tarzan|Jane)".

It’s possible to backtrack into a recursed or repeated group.

You can’t call a group if there is more than one group with that group name or group number ("ambiguous group reference"). For example, (?P<foo>\w+)(?P<foo>\w+)(?&foo)? has 2 groups called “foo” (both group 1) and (?|([A-Z]+)|([0-9]+))(?1)? has 2 groups with group number 1.

The alternative forms (?P>name) and (?P&name) are also supported.

repr(regex) doesn’t include actual regex (issue #13592)

The repr of a compiled regex is now in the form of a eval-able string. For example:

In version 0 behaviour, it uses simple case-folding for backward compatibility with the re module.

Approximate “fuzzy” matching (Hg issue 12, Hg issue 41)

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.

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.)

The 3 types of error are:

Insertion, indicated by “i”

Deletion, indicated by “d”

Substitution, indicated by “s”

In addition, “e” indicates any type of error.

The fuzziness of a regex item is specified between “{” and “}” after the item.

Examples:

foo match “foo” exactly

(?:foo){i} match “foo”, permitting insertions

(?:foo){d} match “foo”, permitting deletions

(?:foo){s} match “foo”, permitting substitutions

(?:foo){i,s} match “foo”, permitting insertions and substitutions

(?:foo){e} match “foo”, permitting errors

If a certain type of error is specified, then any type not specified will not be permitted.

In the following examples I’ll omit the item and write only the fuzziness.

{i<=3} permit at most 3 insertions, but no other types

{d<=3} permit at most 3 deletions, but no other types

{s<=3} permit at most 3 substitutions, but no other types

{i<=1,s<=2} permit at most 1 insertion and at most 2 substitutions, but no deletions

{e<=3} permit at most 3 errors

{1<=e<=3} permit at least 1 and at most 3 errors

{i<=2,d<=2,e<=3} permit at most 2 insertions, at most 2 deletions, at most 3 errors in total, but no substitutions

It’s also possible to state the costs of each type of error and the maximum permitted total cost.

Examples:

{2i+2d+1s<=4} each insertion costs 2, each deletion costs 2, each substitution costs 1, the total cost must not exceed 4

{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

You can also use “<” instead of “<=” if you want an exclusive minimum or maximum:

{e<=3} permit up to 3 errors

{e<4} permit fewer than 4 errors

{0<e<4} permit more than 0 but fewer than 4 errors

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.

The BESTMATCH flag will make it search for the best match instead.

Further examples to note:

regex.search("(dog){e}", "cat and dog")[1] returns "cat" because that matches "dog" with 3 errors, which is within the limit (an unlimited number of errors is permitted).

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 (1 error is permitted).

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 (1 error is permitted), and the (?e) then makes it attempt a better fit.

In the first two examples there are perfect matches later in the string, but in neither case is it the first possible match.

Named lists (Hg issue 11)

\L<name>

There are occasions where you may want to include a list (actually, a set) of options in a regex.

One way is to build the pattern like this:

p = regex.compile(r"first|second|third|fourth|fifth")

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 if they contain any character that has a special meaning in a regex, and that if there is a shorter string that occurs initially in a longer string that the longer string is listed before the shorter one, for example, “cats” before “cat”.

Normally the only line separator is \n (\x0A), but if the WORD flag is turned on then the line separators are the pair \x0D\x0A, and \x0A, \x0B, \x0C and \x0D, plus \x85, \u2028 and \u2029 when working with Unicode.

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).

Set operators

Version 1 behaviour only

Set operators have been added, and a set [...] can include nested sets.

If the following pattern subsequently fails, then the subpattern as a whole will fail.

Possessive quantifiers.

(?:...)?+ ; (?:...)*+ ; (?:...)++ ; (?:...){min,max}+

The subpattern is matched up to ‘max’ times. If the following pattern subsequently fails, then all of the repeated subpatterns will fail as a whole. For example, (?:...)++ is equivalent to (?>(?:...)+).

Scoped flags (issue #433028)

(?flags-flags:...)

The flags will apply only to the subpattern. Flags can be turned on or off.

Inline flags (issue #433024, issue #433027)

(?flags-flags)

Version 0 behaviour: the flags apply to the entire pattern, and they can’t be turned off.

Version 1 behaviour: the flags apply to the end of the group or pattern, and they can be turned on or off.

Repeated repeats (issue #2537)

A regex like ((x|y+)*)* will be accepted and will work correctly, but should complete more quickly.

Definition of ‘word’ character (issue #1693050)

The definition of a ‘word’ character has been expanded for Unicode. It now conforms to the Unicode specification at http://www.unicode.org/reports/tr29/. This applies to \w, \W, \b and \B.

Groups in lookahead and lookbehind (issue #814253)

Groups and group references are permitted in both lookahead and lookbehind.

Variable-length lookbehind

A lookbehind can match a variable-length string.

Correct handling of charset with ignore case flag (issue #3511)

Ranges within charsets are handled correctly when the ignore-case flag is turned on.

Unmatched group in replacement (issue #1519638)

An unmatched group is treated as an empty string in a replacement template.

Groups can be named with (?<name>...) as well as the current (?P<name>...).

Group references

Groups can be referenced within a pattern with \g<name>. This also allows there to be more than 99 groups.

Named characters

\N{name}

Named characters are supported. (Note: only those known by Python’s Unicode database are supported.)

Unicode codepoint properties, including scripts and blocks

\p{property=value}; \P{property=value}; \p{value} ; \P{value}

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}.

If the short form \p{value} is used, the properties are checked in the order: General_Category, Script, Block, binary property:

Latin, the ‘Latin’ script (Script=Latin).

Cyrillic, the ‘Cyrillic’ script (Script=Cyrillic).

BasicLatin, the ‘BasicLatin’ block (Block=BasicLatin).

Alphabetic, the ‘Alphabetic’ binary property (Alphabetic=Yes).

A short form starting with Is indicates a script or binary property:

IsLatin, the ‘Latin’ script (Script=Latin).

IsCyrillic, the ‘Cyrillic’ script (Script=Cyrillic).

IsAlphabetic, the ‘Alphabetic’ binary property (Alphabetic=Yes).

A short form starting with In indicates a block property:

InBasicLatin, the ‘BasicLatin’ block (Block=BasicLatin).

InCyrillic, the ‘Cyrillic’ block (Block=Cyrillic).

POSIX character classes

[[:alpha:]]; [[:^alpha:]]

POSIX character classes are supported. This is actually treated as an alternative form of \p{...}.

Search anchor

\G

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: