Closed AvlWx2014 closed 1 month ago
A minimal example to reproduce that would be:
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]"))
x = A.model_validate({"b": "Abc", "c": "Abc"})
The validation process for b
will succeed, but it will fail for c
. This seems to happen because in the first case, pydantic_core
chooses to use rusts's regex
as the regex engine and in the second case it simply calls pythonic re.Pattern.match
method. The rust Regex.is_match
implementation however, behaves more like python's re.search
, in the docs we can find (emphasis mine):
Returns true if and only if there is a match for the regex anywhere in the haystack given.
I've filed a PR for this.
Issue Description
On Pydantic 2.8.2 with Pydantic-core 2.20.0 I've noticed some inconsistent behavior validating strings using a pattern where passing the pattern as a string allows invalid inputs to pass validation, while passing the pattern as a compiled
Pattern
object fromre.compile
exhibits the expected behavior and rejects the invalid input.Example:
This can be reproduced by adding the following two test cases to tests/validators/test_string.py:
Environment Info
Here is some information on the environment where I noticed the issue: