python
data_error
ai_generated
true
pydantic.errors.StrRegexError: 字符串不符合正则表达式
pydantic.errors.StrRegexError: string does not match regex
ID: python/pydantic-anystr-strict-whitespace
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.
解决方案
-
90% 成功率
Use pattern='^[A-Z]+$' and ensure input is uppercase without spaces
-
85% 成功率
Strip whitespace before validation: @field_validator('field', mode='before') def strip(cls, v): return v.strip()
无效尝试
常见但无效的做法:
-
75% 失败
Pydantic uses re.match by default, but pattern must match entire string; partial matches fail.
-
80% 失败
Whitespace is not stripped unless configured; pattern fails.