python data_error ai_generated true

pydantic.errors.StrRegexError: string does not match regex

ID: python/pydantic-anystr-strict-whitespace

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-01-25First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

When using Field(pattern=...) with a string, the input must fully match the regex; any mismatch raises StrRegexError, often due to whitespace or partial matches.

generic

中文

当使用 Field(pattern=...) 对字符串进行验证时,输入必须完全匹配正则表达式;任何不匹配(如空白字符或部分匹配)都会引发 StrRegexError。

Workarounds

  1. 90% success
    Use pattern='^[A-Z]+$' and ensure input is uppercase without spaces
  2. 85% success
    Strip whitespace before validation: @field_validator('field', mode='before') def strip(cls, v): return v.strip()

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Pydantic uses re.match by default, but pattern must match entire string; partial matches fail.

  2. 80% fail

    Whitespace is not stripped unless configured; pattern fails.