Skip to content
Merged
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
15 changes: 15 additions & 0 deletions Lib/test/test_re.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import re
import sre_compile
import string
import time
import unittest
import warnings
from re import Scanner
Expand Down Expand Up @@ -2038,6 +2039,20 @@ def test_bug_40736(self):
with self.assertRaisesRegex(TypeError, "got 'type'"):
re.search("x*", type)

def test_search_anchor_at_beginning(self):
s = 'x'*10**7
start = time.perf_counter()
for p in r'\Ay', r'^y':
self.assertIsNone(re.search(p, s))
self.assertEqual(re.split(p, s), [s])
self.assertEqual(re.findall(p, s), [])
self.assertEqual(list(re.finditer(p, s)), [])
self.assertEqual(re.sub(p, '', s), s)
t = time.perf_counter() - start
# Without optimization it takes 1 second on my computer.
# With optimization -- 0.0003 seconds.
self.assertLess(t, 0.1)

def test_possessive_quantifiers(self):
"""Test Possessive Quantifiers
Test quantifiers of the form @+ for some repetition operator @,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Optimize :func:`re.search`, :func:`re.split`, :func:`re.findall`,
:func:`re.finditer` and :func:`re.sub` for regular expressions starting with
``\A`` or ``^``.
7 changes: 7 additions & 0 deletions Modules/sre_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -1693,6 +1693,13 @@ SRE(search)(SRE_STATE* state, SRE_CODE* pattern)
state->start = state->ptr = ptr;
status = SRE(match)(state, pattern, 1);
state->must_advance = 0;
if (status == 0 && pattern[0] == SRE_OP_AT &&
(pattern[1] == SRE_AT_BEGINNING ||
pattern[1] == SRE_AT_BEGINNING_STRING))
{
state->start = state->ptr = ptr = end;
return 0;
}
while (status == 0 && ptr < end) {
ptr++;
RESET_CAPTURE_GROUP();
Expand Down