Skip to content

Commit 182d1ab

Browse files
author
Steve Ayers
committed
re2
1 parent 1a28963 commit 182d1ab

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

protovalidate/internal/extra_func.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,18 @@
1313
# limitations under the License.
1414

1515
import math
16-
import re
1716
import typing
1817
from urllib import parse as urlparse
1918

2019
import celpy
20+
import re2
2121
from celpy import celtypes
2222

2323
from protovalidate.internal import string_format
2424
from protovalidate.internal.rules import MessageType, field_to_cel
2525

2626
# See https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
27-
_email_regex = re.compile(
27+
_email_regex = re2.compile(
2828
r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
2929
)
3030

@@ -1553,13 +1553,22 @@ def __peek(self, char: str) -> bool:
15531553
return self._index < len(self._string) and self._string[self._index] == char
15541554

15551555

1556+
def matches(text: str, pattern: str) -> celpy.Result:
1557+
try:
1558+
m = re2.search(pattern, text)
1559+
except re2.error as ex:
1560+
return celpy.CELEvalError("match error", ex.__class__, ex.args)
1561+
return celtypes.BoolType(m is not None)
1562+
1563+
15561564
def make_extra_funcs(locale: str) -> dict[str, celpy.CELFunction]:
15571565
# TODO(#257): Fix types and add tests for StringFormat.
15581566
# For now, ignoring the type.
15591567
string_fmt = string_format.StringFormat(locale) # type: ignore
15601568
return {
15611569
# Missing standard functions
15621570
"format": string_fmt.format,
1571+
"matches": matches,
15631572
# protovalidate specific functions
15641573
"getField": cel_get_field,
15651574
"isNan": cel_is_nan,

tests/matches_test.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Copyright 2023-2025 Buf Technologies, Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.

0 commit comments

Comments
 (0)