我需要確保該字串不包含西里爾字元。我這樣檢查:
from pydantic import basemodel, field class mymodel(basemodel): content_en: str = field(pattern=r"[^а-яА-Я]") data = mymodel(content_en="has wrong content 'йцукен'") print(data) >>> content_en="has wrong content 'йцукен'"
但是當我將包含西里爾字母的字串傳遞到 content_en
欄位時,不會引發錯誤。
預計:
pydantic_core._pydantic_core.validationerror: 1 validation error for mymodel ...
如何檢查正確?
python 3.8
派丹蒂克2.5
解決方案(感謝@chepner):
class MyModel(BaseModel): content_en: str = Field(pattern=r"^[^а-яА-ЯёЁ]*$")
您的模式與包含至少一個非西里爾字元的任何字串匹配,而不是僅由非西里爾字元組成的字串。
>>> mymodel(content_en="has wrong content 'йцукен'") mymodel(content_en="has wrong content 'йцукен'") >>> mymodel(content_en="йцукен") traceback (most recent call last): file "<stdin>", line 1, in <module> file "/users/chepner/py311/lib/python3.11/site-packages/pydantic/main.py", line 164, in __init__ __pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__) pydantic_core._pydantic_core.validationerror: 1 validation error for mymodel content_en string should match pattern '[^а-яА-Я]' [type=string_pattern_mismatch, input_value='йцукен', input_type=str] for further information visit https://errors.pydantic.dev/2.5/v/string_pattern_mismatch
正確的模式是 ^[^а-яА-Я]*$
:
>>> class MyModel(BaseModel): ... content_en: str = Field(pattern=r"^[^а-яА-Я]*$") ... >>> MyModel(content_en="Has wrong content 'йцукен'") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/chepner/py311/lib/python3.11/site-packages/pydantic/main.py", line 164, in __init__ __pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__) pydantic_core._pydantic_core.ValidationError: 1 validation error for MyModel content_en String should match pattern '^[^а-яА-Я]*$' [type=string_pattern_mismatch, input_value="Has wrong content 'йцукен'", input_type=str] For further information visit https://errors.pydantic.dev/2.5/v/string_pattern_mismatch
以上是Pydantic 驗證。檢查字串是否不包含某些字符的詳細內容。更多資訊請關注PHP中文網其他相關文章!