Skip to content

Commit d02dc18

Browse files
committed
string: Use 're.Pattern.search' instead of 're.Pattern.match'
Rust's 'Regex.is_match' behaves like Python's 're.Pattern.search', here's a snippet from the docs of the former: Returns true if and only if there is a match for the regex *anywhere* in the haystack given. Given the implementation of the regex matching mechanism for the 'validators.string.Pattern', this leads to an inconsistent behavior: import re from pydantic import BaseModel, Field class A(BaseModel): b: str = Field(pattern=r"[a-z]") c: str = Field(pattern=re.compile(r"[a-z]")) A.model_validate({"b": "Abc", "c": "Abc"}) In this snippet od code, 'b' will validate fine, but 'c' won't. Since the test cases for string already establish the expected behavior (the Rust's `Regex.is_match` case), let's use `re.Pattern.search` instead of `re.Pattern.match` to unify the results when a `re.Pattern` object is passed. Signed-off-by: Marcin Sobczyk <[email protected]>
1 parent 0e6b377 commit d02dc18

File tree

2 files changed

+3
-1
lines changed

2 files changed

+3
-1
lines changed

‎src/validators/string.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ impl Pattern {
277277
match &self.engine {
278278
RegexEngine::RustRegex(regex) => Ok(regex.is_match(target)),
279279
RegexEngine::PythonRe(py_regex) => {
280-
Ok(!py_regex.call_method1(py, intern!(py, "match"), (target,))?.is_none(py))
280+
Ok(!py_regex.call_method1(py, intern!(py, "search"), (target,))?.is_none(py))
281281
}
282282
}
283283
}

‎tests/validators/test_string.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ def test_str_not_json(input_value, expected):
8080
({'pattern': r'^\d+$'}, '12345', '12345'),
8181
({'pattern': r'\d+$'}, 'foobar 123', 'foobar 123'),
8282
({'pattern': r'^\d+$'}, '12345a', Err("String should match pattern '^\\d+$' [type=string_pattern_mismatch")),
83+
({'pattern': r'[a-z]'}, 'Abc', 'Abc'),
84+
({'pattern': re.compile(r'[a-z]')}, 'Abc', 'Abc'),
8385
# strip comes after length check
8486
({'max_length': 5, 'strip_whitespace': True}, '1234 ', '1234'),
8587
# to_upper and strip comes after pattern check

0 commit comments

Comments
 (0)