MCPcopy
hub / github.com/python-attrs/attrs / matches_re

Function matches_re

src/attr/validators.py:152–197  ·  view source on GitHub ↗

r""" A validator that raises `ValueError` if the initializer is called with a string that doesn't match *regex*. Args: regex (str, re.Pattern): A regex string or precompiled pattern to match against flags (int): Flags that will be passed to the u

(regex, flags=0, func=None)

Source from the content-addressed store, hash-verified

150
151
152def matches_re(regex, flags=0, func=None):
153 r"""
154 A validator that raises `ValueError` if the initializer is called with a
155 string that doesn't match *regex*.
156
157 Args:
158 regex (str, re.Pattern):
159 A regex string or precompiled pattern to match against
160
161 flags (int):
162 Flags that will be passed to the underlying re function (default 0)
163
164 func (typing.Callable):
165 Which underlying `re` function to call. Valid options are
166 `re.fullmatch`, `re.search`, and `re.match`; the default `None`
167 means `re.fullmatch`. For performance reasons, the pattern is
168 always precompiled using `re.compile`.
169
170 .. versionadded:: 19.2.0
171 .. versionchanged:: 21.3.0 *regex* can be a pre-compiled pattern.
172 """
173 valid_funcs = (re.fullmatch, None, re.search, re.match)
174 if func not in valid_funcs:
175 msg = "'func' must be one of {}.".format(
176 ", ".join(
177 sorted((e and e.__name__) or "None" for e in set(valid_funcs))
178 )
179 )
180 raise ValueError(msg)
181
182 if isinstance(regex, Pattern):
183 if flags:
184 msg = "'flags' can only be used with a string pattern; pass flags to re.compile() instead"
185 raise TypeError(msg)
186 pattern = regex
187 else:
188 pattern = re.compile(regex, flags)
189
190 if func is re.match:
191 match_func = pattern.match
192 elif func is re.search:
193 match_func = pattern.search
194 else:
195 match_func = pattern.fullmatch
196
197 return _MatchesReValidator(pattern, match_func)
198
199
200@attrs(repr=False, slots=True, unsafe_hash=True)

Callers 11

ValidatedAttributeClass · 0.90
ReTesterClass · 0.90
MatchTesterClass · 0.90
RePatternTesterClass · 0.90
SearchTesterClass · 0.90
test_reprMethod · 0.90

Calls 1

_MatchesReValidatorClass · 0.85