Match CPython for `$` and `\Z` in `re` patterns #1038
<!-- branch-diff -->
Branch diff: fix/re-end-anchors
| Commit | Message | Production | Test | Docs | Other |
| --- | --- | --: | --: | --: | --: |
| 684e5be37 | Match CPython for $ and \Z in… | +199 -23 | +33 -1 | +0 -0 | +0 -0 |
| c29052c6a | Keep $ off fancy-regex's ba… | +228 -128 | +28 -0 | +11 -0 | +0 -0 |
| 3cc16ab4a | Keep lazily compiled regexes … | +78 -55 | +3 -0 | +2 -1 | +0 -0 |
| | TOTAL | +368 -69 | +64 -1 | +12 -0 | +0 -0 |
<!-- cubic:review-summary:start -->
All reported issues were addressed across 2 files
<!-- cubic:review-summary:end -->
<sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_9f27a37a31d11c75b7c79dc0d001e2da758231cee8d7972cf17faf96162884c8:684e5be37cd00596ee70e89920677fbebf3769d2:8cf5d602-5260-596e-b4dc-376e0565b6d7 -->
<!-- cubic:v=6e10d3da-8827-41d2-92c5-38fd27126d55 -->
<!-- cubic:review-run=8cf5d602-5260-596e-b4dc-376e0565b6d7 -->
<!-- metadata:{"confidence":9} -->
P2: Verbose (?x) comments can contain ) and currently corrupt the MULTILINE scope before this anchor is classified. Scan # comments through the next unescaped newline while verbose mode is active, so (?xm)(?-m:a # )\n$) preserves CPython’s scoped (?-m:...) behavior.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/re_pattern.rs, line 809:
<comment>Verbose `(?x)` comments can contain `)` and currently corrupt the MULTILINE scope before this anchor is classified. Scan `#` comments through the next unescaped newline while verbose mode is active, so `(?xm)(?-m:a # )\n$)` preserves CPython’s scoped `(?-m:...)` behavior.</comment>
<file context>
@@ -688,6 +744,126 @@ fn compile_regex_limited(pattern: &str, flags: u16, delegate_size_limit: Option<
+ out.push(')');
+ multiline = outer.pop().unwrap_or(multiline);
+ }
+ '$' if !multiline => {
+ has_dollar = true;
+ out.push_str(match (dollar_before_newline, chars.peek()) {
</file context>
</details>
✅ Addressed in c29052c
<!-- cubic:v=51f4d433-b86d-4964-8712-83becc49bcdc -->
<!-- cubic:review-run=8cf5d602-5260-596e-b4dc-376e0565b6d7 -->
<!-- metadata:{"confidence":9} -->
P2: A cached $ pattern that sees a trailing-newline subject retains a second full Regex beside the original, so the cache's documented compiled-memory bound no longer holds. Account for both variants in the cache budget or avoid retaining the second one.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/re_pattern.rs, line 81:
<comment>A cached `$` pattern that sees a trailing-newline subject retains a second full `Regex` beside the original, so the cache's documented compiled-memory bound no longer holds. Account for both variants in the cache budget or avoid retaining the second one.</comment>
<file context>
@@ -70,6 +72,13 @@ pub(crate) struct RePattern {
+ /// The pattern compiled with `dollar_before_newline`, built on first use by a subject that
+ /// ends in `\n` (see [`RePattern::for_subject`]). `None` when the pattern has no `$`
+ /// outside MULTILINE, so its regexes already match like Python for every subject.
+ newline_variant: Option<OnceCell<Box<Self>>>,
}
</file context>
</details>
✅ Addressed in 3cc16ab
Codecov Report
:x: Patch coverage is
88.23529% with 24 lines in your changes missing coverage. Please review.| Files with missing lines | Patch % | Lines |
|---|---|---|
| crates/monty/src/types/re\_pattern.rs | 88.23% | 8 Missing and 16 partials :warning: |
:loudspeaker: Thoughts on this report? Let us know!
<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->
Merging this PR will degrade performance by 4.08%
<details>
<summary>:warning: <b>10 benchmarks spent significant time in system calls</b></summary>
System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.
> Measurement and system calls
> - `walk_files__monty
-add_two__monty
-glob_wildcard_overlay__monty
-glob_wildcard__monty
-ext_calls_1000
-pool_create_session_run
-glob_recursive__monty
-glob_recursive_overlay__monty
-session_checkout_run
-ext_call_rows
</details>
<details>
<summary>:warning: <b>Different runtime environments detected</b></summary>
Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.
> Open the report in CodSpeed to investigate
</details>
❌ 1 regressed benchmark ✅ 49 untouched benchmarks ⏩ 16 skipped benchmarks[^skipped]
[!WARNING]
Please fix the performance issues or acknowledge them on CodSpeed.
Performance Changes
| | Benchmark | BASE | HEAD | Efficiency |
| --- | --------- | ------ | ------ | ---------- |
| ❌ :warning: | walk_files__monty | 53.8 ms | 56.1 ms | -4.08% |
[!TIP]
Investigate this regression by commenting @codspeedbot fix this regression` on this PR, or directly use the CodSpeed MCP with your agent.
---
<sub>Comparing <code>Likheet:fix/re-end-anchors</code> (3cc16ab) with <code>main</code> (4246aa7)</sub>
<a href="https://app.codspeed.io/pydantic/monty/branches/Likheet%3Afix%2Fre-end-anchors?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>
[^skipped]: 16 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
Review from Claude
The fix is correct for every case I tried (lookbehind with $, group counting after fancy-regex's explicit group 0, named groups, sub references, re.I, \Z in a class, conditionals, cache reuse across newline and non-newline subjects), and the new test cases pass on both sides. But the rewrite introduces a regression class that I think needs addressing before merge.
1. A mid-pattern $ moves onto the backtracking VM and hits the backtrack limit on ordinary input
A $ at the very end of the pattern becomes (?=\n?\z), which fancy-regex's optimizer turns into (X)\n?\z and delegates to the linear engine. Everywhere else it becomes (?:\z|(?=\n\z)), which is "hard" and runs on the backtracking VM. That VM counts backtracks per run call, and an unanchored search is a single run looping over every start position (compile.rs emits the .*? split), so the 1,000,000 limit accumulates across the whole subject.
On a subject of repeated word ending in end\n (debug build):
| pattern | 100 kB | 150 kB | 200 kB | main (400 kB) | CPython |
| --- | --- | --- | --- | --- | --- |
| \w+$\|zz | ok | ok | PatternError | [] in 6 ms | ['end'] |
| \w+(?=,\|$) | ok | PatternError | PatternError | [] in 9 ms | ['end'] |
| \w+(?:,\|$) | ok | PatternError | PatternError | [] | ['end'] |
| (\w+)$\|zz | ok | ok | PatternError | [] | ['end'] |
The error is re.PatternError: Error executing regex: Max limit for backtracking count exceeded. (?=,|$) and (?:\s|$) are about the most common idioms people (and LLMs) write, and the failure is input-dependent: it works on text.strip() and raises on the contents of a file. main gave the wrong answer here, but linearly and silently, and the backtrack limit isn't mentioned in limitations/re.md at all today.
The same mechanism hits match/fullmatch for the common ^...$ shape: the \A(?:…) wrapper puts a ) after the $, so it takes the alternation form and the VM. re.match(r'^\d+$', '123\n') x20k went from 43 ms on main to 115 ms in a debug build, matching the 2x in the PR description. Mid-pattern searches that don't error are much slower: re.split(r',|$', big) went from 0.5 ms to 79 ms.
Suggestions, in order of value:
$ out of the wrappers: match → \A(?:X)(?=\n?\z) (trailing lookahead, so delegated), fullmatch → \A(?:X)\z (the $ is redundant before \z). translate_end_anchors already tracks depth, so "last char, depth 0, no top-level |" is cheap to detect.$ that ends an alternative can be \n?\z rather than a nested lookahead, since the context is already zero-width. That keeps \w+(?=,|$) on the linear engine.limitations/re.md: which $ placements, that the backtrack limit raises PatternError, and that the VM's backtrack stack isn't tracked by the resource limits.2. cubic's memory comment: directionally right, but the documented bound was already loose
A cached entry already retains up to three regexes (plain, match, fullmatch), and fancy-regex documents delegate_size_limit as a per-delegated-sub-regex cap. The variant doubles that to six regexes plus a second copy of the source text, so the theoretical worst case goes from ~49 MB to ~98 MB. I'd fix the comments on delegate_size_limit and CACHE_CAPACITY rather than add accounting.
Separately, newline_variant: Option<OnceCell<Box<Self>>> duplicates pattern, flags, delegate_size_limit and an always-None nested variant. A small CompiledSet { compiled, compiled_match, compiled_fullmatch } held twice would be cleaner and drop the pattern.clone().
3. cubic's verbose-comment comment: correct, but not a regression
Monty passes inline (?x) through to fancy-regex, so # comments are live, and for cubic's exact pattern the branch returns [] where CPython returns ['a']. main also returns [], so nothing got worse, and it takes (?x), a # comment containing a paren, and a scoped (?-m:…) group together. Because the translator copies text verbatim and only touches $/\Z, a misparse can only mis-track MULTILINE, never corrupt the pattern. inline_flags already sees the x flag, so skipping # to end of line while it's on is a few lines. Low priority either way.
Smaller notes
translate_end_anchors runs twice per compile (once inside compile_regex_limited, once just for has_dollar). Return the flag from the first call.CACHED_SIZE_LIMIT when the base didn't, the user gets a PatternError from search() rather than a result. I couldn't construct a case, but the path exists.[[:alpha:]$]: the translator reads classes like Python but the regex crate reads nested sets, so the rewritten $ lands inside a class. main, this branch and CPython all give different answers; a pre-existing divergence, just a different wrong answer now.Thanks for the review, all three points were right. I pushed c29052c with these changes.
1. The backtracking VM
match() now puts a final $ that applies to the whole pattern after its wrapper, \A(?:X)$, so it stays a trailing lookahead. fullmatch() drops it: \A(?:X)\z.translate_end_anchors decides this: the $ must be the last character, outside every group, with no top-level | and no re.MULTILINE. With a top-level |, only fullmatch() drops it.$ that ends an alternative of a lookahead becomes \n?\z, so \w+(?=,|$) stays on the linear engine.limitations/re.md now has the backtrack limit, that the steps add up over start positions, that the VM's backtrack stack isn't tracked, and the $ placements that still need the VM.I didn't find a linear form for a
$ inside a group that isn't a lookahead, like \w+(?:,|$), since it has to stay zero-width there.Your table, in a debug build on Windows (subjects of repeated word ending in end\n; 20k calls, best of 5 for the last two rows):
| | previous commit | this commit |
| --- | --- | --- |
| re.findall(r'\w+(?=,\|$)', s), 150 kB to 400 kB | PatternError | ['end'] in 6 to 17 ms |
| \w+(?:,\|$), \w+$\|zz, (\w+)$\|zz | PatternError from 150 to 200 kB | unchanged, now in limitations/re.md |
| re.match(r'^\d+$', '123\n') | 388 ms | 265 ms (235 ms for '123') |
| re.fullmatch(r'^\d+$', '123\n') | 318 ms | 136 ms |
2. Memory
RePattern now holds two CompiledSet { compiled, compiled_match, compiled_fullmatch }, so there is no Box<Self> and no pattern.clone().
The comments on delegate_size_limit, CACHE_CAPACITY and CACHED_SIZE_LIMIT now say that an entry can hold six regexes and that the limit applies per delegated sub-regex.
3. Verbose comments
# now runs to the end of the line while x is on, followed through inline and scoped flags like MULTILINE.
This mattered more after the lookahead change: in (?x)a(?=(b # )\n|$)), the ) in the comment closed the capture group early, so the $ looked like it ended the lookahead and group 1 captured the \n.
That pattern and cubic's are both tests now.
Smaller notes
translate_end_anchors runs once per compile: compile_regex_limited returns what it found.CACHED_SIZE_LIMIT is now compiled at the default limit instead of raising PatternError (compile_lazily), and the comments say it can be retained slightly over the cap.[[:alpha:]$] as it is, since it's a separate divergence.Testing
re__basic.py. The 250 kB lookahead one and cubic's verbose one fail on the previous commit, and the other verbose one fails when the # handling is removed.$ in all of the placements above, re.M, inline and scoped MULTILINE, and (?x) comments holding ) and |, on subjects with and without a trailing \n.All 157,275
search, match, fullmatch, findall, sub and split calls give the same output as the previous commit.Against CPython 3.14.0 the only differences are in
findall, sub and split, from the empty-match iteration rule, and they are the same set as on the previous commit.cargo test -p monty passes, and the datatest suite passes on the Monty side.The 11 CPython-side cases that fail on this machine (CPython 3.14.0) don't run Monty code, and none of them is an
re case.monty with --tests --all-features -D warnings, scripts/check_imports.py, rustfmt, and ruff on the test file pass.Changed in c29052c as Samuel suggested in his review: the regexes for subjects ending in \n are now a second CompiledSet without their own copy of the pattern, and instead of adding accounting, the comments on CACHE_CAPACITY, CACHED_SIZE_LIMIT and delegate_size_limit now give the real bound: an entry can hold six regexes, and the limit applies per delegated sub-regex.
<!-- cubic:v=fd84cdcd-24f9-4d4e-98b1-e230ca067c5f -->
<!-- cubic:review-run=bf87909e-2ee9-5e03-8a73-922a86a2052f -->
<!-- metadata:{"confidence":9} -->
P1: This fallback bypasses the cache's compiled-size bound and the resulting regex is retained in newline_regexes. A pattern can fit the bounded unanchored compile but expand past the limit when $ is rewritten, letting repeated cached patterns retain substantially oversized regexes and undermine the cache's memory protection. Keep over-limit lazy variants out of the retained cache, or use a bounded/evictable representation for them.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/re_pattern.rs, line 244:
<comment>This fallback bypasses the cache's compiled-size bound and the resulting regex is retained in `newline_regexes`. A pattern can fit the bounded unanchored compile but expand past the limit when `$` is rewritten, letting repeated cached patterns retain substantially oversized regexes and undermine the cache's memory protection. Keep over-limit lazy variants out of the retained cache, or use a bounded/evictable representation for them.</comment>
<file context>
@@ -139,89 +158,103 @@ impl RePattern {
+ let compiled = match compile_regex_limited(source, self.flags, self.delegate_size_limit, dollar_before_newline)
+ {
+ Err(err) if self.delegate_size_limit.is_some() && is_size_limit_error(&err) => {
+ compile_regex_limited(source, self.flags, None, dollar_before_newline)
+ }
+ result => result,
</file context>
</details>
✅ Addressed in 3cc16ab
<!-- cubic:v=6e639902-c852-4165-bac6-2461bef3aaa4 -->
<!-- cubic:review-run=bf87909e-2ee9-5e03-8a73-922a86a2052f -->
<!-- metadata:{"confidence":8} -->
P2: A $ followed only by ignored verbose whitespace or a comment is still the pattern's trailing anchor, but this check leaves it unclassified and rewrites it into an internal lookahead on newline subjects. Long matches can consequently hit the backtracking limit; classify trailing anchors after skipping verbose trivia.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/re_pattern.rs, line 890:
<comment>A `$` followed only by ignored verbose whitespace or a comment is still the pattern's trailing anchor, but this check leaves it unclassified and rewrites it into an internal lookahead on newline subjects. Long matches can consequently hit the backtracking limit; classify trailing anchors after skipping verbose trivia.</comment>
<file context>
@@ -790,34 +862,60 @@ fn translate_end_anchors(pattern: &str, multiline: bool, dollar_before_newline:
+ anchors.has_dollar = true;
+ let next = chars.peek().copied();
+ // moved out of a `match()` wrapper, the `$` must still be outside MULTILINE
+ if next.is_none() && open.is_empty() && !multiline {
+ anchors.trailing_dollar = if top_level_alternation {
+ TrailingDollar::LastAlternative
</file context>
</details>
✅ Addressed in 3cc16ab
<!-- cubic:v=965492b9-4690-476b-95d7-b88acb3116bf -->
<!-- cubic:review-run=bf87909e-2ee9-5e03-8a73-922a86a2052f -->
<!-- metadata:{"confidence":8} -->
P2: The backtracking stack's allocator-backed allocations still count toward max_memory. Clarify that matching does not poll resource limits during backtracking instead of saying its memory is untracked.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/limitations/re.md, line 98:
<comment>The backtracking stack's allocator-backed allocations still count toward `max_memory`. Clarify that matching does not poll resource limits during backtracking instead of saying its memory is untracked.</comment>
<file context>
@@ -88,3 +88,14 @@ representation does not carry them.
+ it has taken 1,000,000 backtracking steps, where CPython continues.
+ The steps add up over every start position the search tries, so a pattern can work on a short subject and raise on a
+ long one whose next match is far from where the search starts.
+ The VM's backtracking stack is not tracked by the resource limits.
+- For a subject ending in `\n`, a `$` outside MULTILINE also puts the pattern on that VM, unless the `$` ends the
+ pattern or ends an alternative of a lookahead that ends the pattern.
</file context>
</details>
Matching does not poll resource limits while backtracking, though its stack allocations still count toward `max_memory` and the allocator hard limit.
✅ Addressed in 3cc16ab
<!-- cubic:review-summary:start -->
All reported issues were addressed across 4 files (changes from recent commits).
<!-- cubic:review-summary:end -->
<sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_664736311eb68fff0b7eb0a4e1e8b91771248a29d93829d06022b28915bce144:c29052c6abd6152283e099faf9c307190c0e9267:bf87909e-2ee9-5e03-8a73-922a86a2052f -->
Fixed in 3cc16ab: a lazily compiled form over the size cap is now compiled at the default limit for that call only and not kept in the entry, as the cache does with a pattern over its cap. For example, at the smallest limit a{100}$ compiles at (3,440), its newline form does not fit, and it is now returned per call without being stored.
Fixed in 3cc16ab: under (?x) the rewrite now takes the next character past whitespace and # comments, so (?x)\w+$ # comment and (?x)\w+ (?= , | $ ) stay linear; both are tests on a 250 kB subject. match() still only moves a $ that is the last character, since it cuts that character off the pattern text.
Fixed in 3cc16ab: the sentence now says that the stack counts toward max_memory, but no checkpoint runs during a search, so only the hard ceiling applies to it, with a link to resource_limits.md.
Follow-up in 3cc16ab, for cubic's review of c29052c:
CACHED_SIZE_LIMIT is no longer kept: it is compiled at the default limit for the call only, like a pattern over the cache's cap. So the part of my reply above about retaining it slightly over the cap no longer applies.(?x), a $ followed only by whitespace or a comment now gets the same rewrite as one with nothing after it.limitations/re.md now says that the backtracking stack counts toward max_memory, but only the hard ceiling applies to it during a search.
samuelcolvin
Likheet
fancy-regex reads
$and\Zdifferently from Python'sre.Python's
$outside MULTILINE also matches before a newline that ends the string, where fancy-regex's$is only the very end.Python's
\Zis only the very end, where fancy-regex's\Zalso allows trailing newlines.So a check on a line that still has its newline fails, and
\Zaccepts trailing newlines:| | Monty
main| CPython 3.14 || --- | --- | --- |
|
re.match(r'^\d+$', '123\n')|None| match'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):\Zbecomes\z, and$outside MULTILINE becomes(?=\n?\z)at the end of the pattern,\n?\zwhere 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 throughre.M, inline(?m)and scoped(?m:...)/(?-m:...)groups.Pattern.patternkeeps 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
PatternErrorafter 1,000,000 backtracking steps in one search.So
RePatternholds twoCompiledSets: 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 throughfor_subject.A
$at the end of the pattern stays a trailing lookahead, which keepsre.search(r'end$', text)on a 400 kB string ending in\nat about 0.1 ms.match()moves a final$that applies to the whole pattern after its\A(?:...)wrapper, andfullmatch()drops it before\z, sore.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 raisePatternErroron long subjects ending in\n, solimitations/re.mdnow lists them with the backtrack limit.Testing
re__basic.pyfail onmainand pass on Monty and CPython 3.14. They covermatch,search,fullmatch,findall,subandsplitwith 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.$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.search,match,fullmatch,finditer,subandsplitcalls against CPython 3.14.7 and amainbuild. The patterns mix$,\Z,\z,^,\Aand\bwith 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\Zgive byte-identical results tomain, including the error messages.- 1,029 calls that differed from CPython on
mainnow match it, and none that matched stopped matching.- The 1,546 that still differ come from two limits that exist on
maintoo: 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.$at the end, in the middle, after a top-level|, in lookaheads and capture groups, underre.M, inline and scoped MULTILINE and(?x)comments holding)and|, on subjects with and without a trailing\n.re.match(r'^\d+$', line)calls take 235 ms for lines without\nand 265 ms for the same lines ending in\n(best of 5 runs).cargo test -p montypasses, and the datatest suite passes on the Monty side. The CPython-side cases that fail for me also fail onmainin my environment; none of them is anrecase.#1036 adds
split_with_groups, which readsself.compileddirectly.Whichever of the two is merged second should use
self.for_subject(text)?.compiledthere, like the other methods; with that change the three open branches (#1033, #1036 and this one) pass the suite together.<!-- This is an auto-generated description by cubic. -->
---
Summary by cubic
Fixes
repattern anchors$and\Zto match CPython:$outside MULTILINE now also matches before a trailing newline, and\Zmatches only at the very end.Patterns are rewritten before compiling (
\Zbecomes\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, andPattern.patternkeeps the original text. A final$is kept outside thematch()/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
re__basic.pycovermatch,search,fullmatch,findall,sub, andsplitwith trailing newlines, plus$in classes, escapes, comments, repeated groups, lookahead alternatives, and scoped/inline MULTILINE.$/\Z; remaining differences are pre-existing iteration limits.limitations/re.mddocuments the backtracking limit, the$placements that still need the VM, and that the backtracking stack counts towardmax_memory.split_with_groupson#1036readsself.compileddirectly; whichever branch merges second should switch it toself.for_subject(text)?.compiled.<sup>Written for commit 3cc16ab4a1844962740a6a6b6d5d8b6113452c98. Summary will update on new commits.</sup>
<a href="https://cubic.dev/pr/pydantic/monty/pull/1038?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->