Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Multiline regexes starting with a caret, such as ``re.compile("^foo",
re.MULTILINE)``, now run significantly faster.
23 changes: 23 additions & 0 deletions Modules/_sre/sre_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -1848,6 +1848,29 @@ SRE(search)(SRE_STATE* state, SRE_CODE* pattern)
ptr++;
RESET_CAPTURE_GROUP();
}
} else if (pattern[0] == SRE_OP_AT &&
pattern[1] == SRE_AT_BEGINNING_LINE) {
/* pattern is anchored at the start of a line (MULTILINE "^").
Only the start of the string and the character after a linebreak
can match, so jump from one line start to the next instead of
trying SRE(match) at every position. */
end = (SRE_CHAR *)state->end;
TRACE(("|%p|%p|SEARCH AT_BEGINNING_LINE\n", pattern, ptr));
state->start = state->ptr = ptr;
status = SRE(match)(state, pattern, 1);
state->must_advance = 0;
while (status == 0) {
/* skip to the next linebreak ... */
while (ptr < end && !SRE_IS_LINEBREAK(*ptr))
ptr++;
if (ptr >= end)
return 0;
Comment on lines +1864 to +1867

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be

Suggested change
while (ptr < end && !SRE_IS_LINEBREAK(*ptr))
ptr++;
if (ptr >= end)
return 0;
+#if SIZEOF_SRE_CHAR == 1
ptr = memchr(ptr, '\n', end - ptr);
if (ptr == NULL)
return 0;
#else
while (ptr < end && !SRE_IS_LINEBREAK(*ptr))
ptr++;
if (ptr >= end)
return 0;
#endif

(I did not benchmark, not sure it is worth the change)

ptr++; /* ... and step past it, onto a line start */
RESET_CAPTURE_GROUP();
TRACE(("|%p|%p|SEARCH AT_BEGINNING_LINE\n", pattern, ptr));
state->start = state->ptr = ptr;
status = SRE(match)(state, pattern, 0);
}
} else {
/* general case */
assert(ptr <= end);
Expand Down
Loading