Match CPython for `$` and `\Z` in `re` patterns

LI
1mo ago
+458-74

fancy-regex reads $ and \Z differently from Python's re.
Python's $ outside MULTILINE also matches before a newline that ends the string, where fancy-regex's $ is only the very end.
Python's \Z is only the very end, where fancy-regex's \Z also allows trailing newlines.
So a check on a line that still has its newline fails, and \Z accepts trailing newlines:

Monty mainCPython 3.14
re.match(r'^\d+$', '123\n')Nonematch '123'
re.findall(r'\w+$', 'line1\nline2\n')[]['line2']
re.sub(r'$', '!', 'a\n')'a\n!''a!\n!'
re.search(r'ab\Z', 'ab\n')match 'ab'None
re.findall(r'(?-m:\w+$)', 'ab\ncd\n', re.M)[]['cd']

Neither is in limitations/re.md.

Patterns are now rewritten before compiling (translate_end_anchors): \Z becomes \z, and $ outside MULTILINE becomes (?=\n?\z) at the end of the pattern, \n?\z where it ends an alternative of a lookahead, and (?:\z|(?=\n\z)) anywhere else.
The rewrite reads the pattern as Python does: escapes, classes, (?#...) comments and # comments under (?x) are copied, and MULTILINE and VERBOSE are followed through re.M, inline (?m) and scoped (?m:...) / (?-m:...) groups.
Pattern.pattern keeps the original text.

The $ rewrite needs a lookaround, and it only changes a result when the subject ends in \n.
fancy-regex runs a lookahead on its linear engine only when the lookahead ends the pattern; anywhere else the pattern moves to its backtracking VM, which is slower and raises PatternError after 1,000,000 backtracking steps in one search.
So RePattern holds two CompiledSets: its current regexes for every other subject, and the rewritten ones, built on first use by a subject ending in \n. Each method picks one through for_subject.
A $ at the end of the pattern stays a trailing lookahead, which keeps re.search(r'end$', text) on a 400 kB string ending in \n at about 0.1 ms.
match() moves a final $ that applies to the whole pattern after its \A(?:...) wrapper, and fullmatch() drops it before \z, so re.match(r'^\d+$', line) stays linear too.
A $ that ends an alternative of a lookahead can consume the \n, since the lookahead is zero-width already, which keeps \w+(?=,|$) linear.
Anywhere else the $ is an alternation, since fancy-regex won't repeat a bare lookahead, as in (?:$)*.
Those placements, like \w+(?:,|$), now raise PatternError on long subjects ending in \n, so limitations/re.md now lists them with the backtrack limit.

Testing

  • New asserts in re__basic.py fail on main and pass on Monty and CPython 3.14. They cover match, search, fullmatch, findall, sub and split with a trailing newline, \Z, scoped and inline MULTILINE, $ in a class, escaped, after an escaped backslash and in a comment, and $ in a repeated group.
  • The second commit adds asserts for a final $ with and without a top-level |, $ in lookaheads, a 250 kB subject and (?x) comments that hold a ). The 250 kB one and cubic's (?x) one fail on the first commit, and the other (?x) one fails when the # handling is removed.
  • 32,000 generated search, match, fullmatch, finditer, sub and split calls against CPython 3.14.7 and a main build. The patterns mix $, \Z, \z, ^, \A and \b with scoped and inline flags, classes, escapes and comments, and the subjects end with and without newlines.
    • The 12,053 calls whose pattern has no $ or \Z give byte-identical results to main, including the error messages.
    • 1,029 calls that differed from CPython on main now match it, and none that matched stopped matching.
    • The 1,546 that still differ come from two limits that exist on main too: an empty match right after the previous match is skipped (all 1,470 such calls come out the same when CPython's own engine is run with fancy-regex's iteration rule), and a group holding only a (?#...) comment can't be repeated.
  • The second commit gives the same output as the first on 157,275 further calls: 4,500 generated patterns with $ at the end, in the middle, after a top-level |, in lookaheads and capture groups, under re.M, inline and scoped MULTILINE and (?x) comments holding ) and |, on subjects with and without a trailing \n.
  • In a debug build, 20,000 re.match(r'^\d+$', line) calls take 235 ms for lines without \n and 265 ms for the same lines ending in \n (best of 5 runs).
  • cargo test -p monty passes, and the datatest suite passes on the Monty side. The CPython-side cases that fail for me also fail on main in my environment; none of them is an re case.

#1036 adds split_with_groups, which reads self.compiled directly.
Whichever of the two is merged second should use self.for_subject(text)?.compiled there, like the other methods; with that change the three open branches (#1033, #1036 and this one) pass the suite together.


Summary by cubic

Fixes re pattern anchors $ and \Z to match CPython: $ outside MULTILINE now also matches before a trailing newline, and \Z matches only at the very end.

Patterns are rewritten before compiling (\Z becomes \z, $ becomes a lookahead), but a faster base regex is kept for subjects that don't end in \n; the rewritten variant compiles lazily only for subjects ending in \n, and Pattern.pattern keeps the original text. A final $ is kept outside the match()/fullmatch() anchors and a $ ending a lookahead alternative becomes \n?\z, so both run on fancy-regex's linear engine. A lazily compiled form over the cache's size cap recompiles at the default limit for that call only. Under (?x), rewriting skips whitespace and # comments, so a $ followed by a comment still ends the pattern or a lookahead alternative.

Testing

  • New assertions in re__basic.py cover match, search, fullmatch, findall, sub, and split with trailing newlines, plus $ in classes, escapes, comments, repeated groups, lookahead alternatives, and scoped/inline MULTILINE.
  • Generated comparisons against CPython 3.14.7 show no regressions on patterns without $/\Z; remaining differences are pre-existing iteration limits.
  • limitations/re.md documents the backtracking limit, the $ placements that still need the VM, and that the backtracking stack counts toward max_memory.

split_with_groups on #1036 reads self.compiled directly; whichever branch merges second should switch it to self.for_subject(text)?.compiled.