python data_error ai_generated true

pydantic.errors.StrRegexError: 字符串不符合正则表达式

pydantic.errors.StrRegexError: string does not match regex

ID: python/pydantic-anystr-strict-whitespace

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-01-25首次发现

版本兼容性

版本状态引入弃用备注
2.x active

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 75% 失败

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

  2. 80% 失败

    Whitespace is not stripped unless configured; pattern fails.