You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python的jsonschema使用regex模块验证Unicode正则pattern?

解决jsonschema中Unicode正则表达式(\p{L})的校验问题

问题核心是jsonschema默认依赖Python内置的re模块,而re不支持Unicode属性类(如\p{L}),但第三方regex模块支持。要让jsonschema使用regex模块替代默认的正则校验逻辑,需要自定义验证器:

实现步骤

  • 继承jsonschema的默认验证器(比如Draft7Validator,根据你使用的JSON Schema版本选择)
  • 重写验证器中处理pattern关键字的方法,改用regex模块编译和匹配正则
  • 使用自定义验证器完成实例校验

完整代码示例

import jsonschema
from jsonschema.validators import Draft7Validator
import regex

schema = {
    "type": "object",
    "properties": {
        "name": {
            "type": "string",
            # 用原始字符串避免转义问题
            "pattern": r"[\p{L}]+",
        },
    },
}

# 自定义验证器,重写pattern校验逻辑
class RegexPatternValidator(Draft7Validator):
    def _validate_pattern(self, pattern, instance, schema):
        # 用regex模块编译正则
        try:
            regex_obj = regex.compile(pattern)
        except regex.error as e:
            raise jsonschema.exceptions.SchemaError(
                f"'{pattern}' is not a valid regex: {e}"
            ) from e
        
        # 执行匹配校验
        if not regex_obj.search(instance):
            raise jsonschema.exceptions.ValidationError(
                f"'{instance}' does not match pattern '{pattern}'"
            )

# 测试regex模块匹配
if regex.compile(schema["properties"]["name"]["pattern"]).search("ᚠᛇᚻ"):
    print("It matched")

# 使用自定义验证器校验实例
RegexPatternValidator(schema).validate(instance={"name": "ᚠᛇᚻ"})
print("Validation passed!")

关键说明

  1. 验证器继承:选择对应JSON Schema版本的验证器(如Draft7Validator对应JSON Schema Draft 7),确保兼容性。
  2. 重写_validate_pattern方法:这个方法是jsonschema内置处理pattern关键字的核心逻辑,替换成regex模块的实现后,就能支持Unicode属性类。
  3. 异常处理:保留了原有的异常抛出逻辑,确保正则无效时仍能抛出SchemaError,匹配失败时抛出ValidationError,和默认行为一致。

运行这段代码后,regex模块的匹配和自定义验证器的校验都会成功执行,不会再抛出原有的SchemaError。

内容的提问来源于stack exchange,提问作者user1751825

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 20:13:28