Skip to content

Commit 47a702e

Browse files
committed
improved regex cache
1 parent 030aa6f commit 47a702e

1 file changed

Lines changed: 6 additions & 8 deletions

File tree

packages/google-api-core/google/api_core/path_template.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def _validate_multi_segment_value(val: str) -> bool:
114114

115115

116116
@functools.lru_cache(maxsize=1024)
117-
def _build_capture_pattern(template_str: str) -> tuple[str, tuple[str, ...]]:
117+
def _build_capture_pattern(template_str: str) -> tuple[re.Pattern, tuple[str, ...]]:
118118
"""Build a regex pattern to capture wildcard matches from a template.
119119
120120
This function parses a template string containing positional/named
@@ -126,7 +126,7 @@ def _build_capture_pattern(template_str: str) -> tuple[str, tuple[str, ...]]:
126126
template_str (str): The template string (e.g. "projects/*/locations/*").
127127
128128
Returns:
129-
tuple[str, list[str]]: A tuple containing:
129+
tuple[re.Pattern, tuple[str, ...]]: A tuple containing:
130130
- The compiled regex pattern string with capture groups.
131131
- A list of wildcard type strings ('*' or '**') in matching order.
132132
"""
@@ -153,7 +153,7 @@ def replacer(match):
153153
else:
154154
sub_pattern, sub_types = _build_capture_pattern(template)
155155
wildcard_types.extend(sub_types)
156-
return sub_pattern
156+
return sub_pattern.pattern
157157
return match.group(0)
158158

159159
parts = []
@@ -168,8 +168,7 @@ def replacer(match):
168168
parts.append(re.escape(literal))
169169

170170
pattern = "".join(parts)
171-
# Convert wildcard_types to a tuple to ensure the return value is fully hashable and robust
172-
return pattern, tuple(wildcard_types)
171+
return re.compile(pattern), tuple(wildcard_types)
173172

174173

175174
def _extract_and_validate_wildcards(
@@ -223,10 +222,9 @@ def _extract_and_validate_wildcards(
223222
return
224223

225224
# Sub-template case: use cached capture pattern and regex match
226-
pattern_body, wildcard_types = _build_capture_pattern(template_str)
227-
pattern = "^" + pattern_body + "$"
225+
pattern, wildcard_types = _build_capture_pattern(template_str)
228226

229-
m = re.match(pattern, val)
227+
m = pattern.fullmatch(val)
230228
if m is not None:
231229
for i, wildcard_type in enumerate(wildcard_types):
232230
captured_val = m.group(i + 1)

0 commit comments

Comments
 (0)