问题描述
我正在使用正则表达式来验证json模式中的属性。
架构如下:
{
"$schema": "http://json-schema.org/draft-07/schema","$id": "http://example.com/example.json","type": "object","required": [
"library_version"
],"properties": {
"library_version": {
"$id": "#/properties/library_version","type": "string","title": "Library version","description": "The library version (e.g. 0.0.1) used to create this file.","pattern": "^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$","message": {
"required": "Library version is a required property","pattern": "The version must be a semantic form,like 0.0.1 (see https://semver.org/)"
},"examples": [
"0.0.1"
]
}
}
}
大正则表达式用于semver - c.f. here。
使用jsonlint我得到:
Error: Parse error on line 14:
...le.","pattern": "^(0|[1-9]\d*)\.(0|[
----------------------^
Expecting 'STRING','NUMBER','NULL','TRUE','FALSE','{','[',got 'undefined'
我当然不必在json模式中转义正则表达式模式吗?字符串应视为文字,对吗?有谁知道这到底是怎么回事?
解决方法
即使在文字字符串中,也不能使用某些字符而不能转义:https://www.freeformatter.com/json-escape.html
您的正则表达式必须转义所有反斜杠(您可以使用链接中的工具进行此操作)。