Skip to content

Commit ab4bf9f

Browse files
committed
gh-148762: speed up caret match in regexes
Signed-off-by: Harmen Stoppels <harmenstoppels@gmail.com>
1 parent 5a549e8 commit ab4bf9f

2 files changed

Lines changed: 15 additions & 0 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Multiline regexes starting with a caret, such as ``re.compile("^foo",
2+
re.MULTILINE)``, now run significantly faster.

Modules/_sre/sre_lib.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1863,6 +1863,19 @@ SRE(search)(SRE_STATE* state, SRE_CODE* pattern)
18631863
return 0;
18641864
}
18651865
while (status == 0 && ptr < end) {
1866+
if (pattern[0] == SRE_OP_AT &&
1867+
pattern[1] == SRE_AT_BEGINNING_LINE &&
1868+
(void*) ptr > state->beginning &&
1869+
!SRE_IS_LINEBREAK((int) ptr[-1]))
1870+
{
1871+
/* fast-forward to the next newline character */
1872+
while (ptr < end && !SRE_IS_LINEBREAK((int) *ptr)) {
1873+
ptr++;
1874+
}
1875+
if (ptr >= end) {
1876+
return 0;
1877+
}
1878+
}
18661879
ptr++;
18671880
RESET_CAPTURE_GROUP();
18681881
TRACE(("|%p|%p|SEARCH\n", pattern, ptr));

0 commit comments

Comments
 (0)