diff --git a/pydantic/_internal/_config.py b/pydantic/_internal/_config.py index 61d3c303a5..a4052cada6 100644 --- a/pydantic/_internal/_config.py +++ b/pydantic/_internal/_config.py @@ -80,6 +80,7 @@ class ConfigWrapper: json_schema_serialization_defaults_required: bool json_schema_mode_override: Literal['validation', 'serialization', None] coerce_numbers_to_str: bool + regex_engine: Literal['rust-regex', 'python-re'] def __init__(self, config: ConfigDict | dict[str, Any] | type[Any] | None, *, check: bool = True): if check: @@ -176,6 +177,7 @@ def dict_not_none(**kwargs: Any) -> Any: str_min_length=self.config_dict.get('str_min_length'), hide_input_in_errors=self.config_dict.get('hide_input_in_errors'), coerce_numbers_to_str=self.config_dict.get('coerce_numbers_to_str'), + regex_engine=self.config_dict.get('regex_engine'), ) ) return core_config @@ -248,6 +250,7 @@ def _context_manager() -> Iterator[None]: json_schema_serialization_defaults_required=False, json_schema_mode_override=None, coerce_numbers_to_str=False, + regex_engine='rust-regex', ) diff --git a/pydantic/config.py b/pydantic/config.py index cb8bc2e464..a2cbe34780 100644 --- a/pydantic/config.py +++ b/pydantic/config.py @@ -787,5 +787,38 @@ class Model(BaseModel): ``` """ + regex_engine: Literal['rust-regex', 'python-re'] + """ + The regex engine to used for pattern validation + Defaults to `'rust-regex'`. + + - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate, + which is non-backtracking and therefore more DDoS resistant, but does not support all regex features. + - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module, + which supports all regex features, but may be slower. + + ```py + from pydantic import BaseModel, ConfigDict, Field, ValidationError + + class Model(BaseModel): + model_config = ConfigDict(regex_engine='python-re') + + value: str = Field(pattern=r'^abc(?=def)') + + print(Model(value='abcdef').value) + #> abcdef + + try: + print(Model(value='abxyzcdef')) + except ValidationError as e: + print(e) + ''' + 1 validation error for Model + value + String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str] + ''' + ``` + """ + __getattr__ = getattr_migration(__name__)