我需要满足仅接受 MM/DD/YYYY 形式的值的要求。
根据我读到的内容:https://www.w3.org/TR/xmlschema11-2/#nt-dateRep 使用
<xs:simpleType name="DATE">
<xs:restriction base="xs:date"/>
</xs:simpleType>
不会工作,因为它的正则表达式显然不支持这种格式。
我找到并调整了这种格式:
^(?:(?:(?:0?[13578]|1[02])(\/)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
此表格:
\^\(\?:\(\?:\(\?:0\?\[13578\]\|1\[02\]\)\(\\/\)31\)\1\|\(\?:\(\?:0\?\[1,3-9\]\|1\[0-2\]\)\(\\/\)\(\?:29\|30\)\2\)\)\(\?:\(\?:1\[6-9\]\|\[2-9\]\d\)\?\d{2}\)$\|\^\(\?:0\?2\(\\/\)29\3\(\?:\(\?:\(\?:1\[6-9\]\|\[2-9\]\d\)\?\(\?:0\[48\]\|\[2468\]\[048\]\|\[13579\]\[26\]\)\|\(\?:\(\?:16\|\[2468\]\[048\]\|\[3579\]\[26\]\)00\)\)\)\)$\|\^\(\?:\(\?:0\?\[1-9\]\)\|\(\?:1\[0-2\]\)\)\(\\/\)\(\?:0\?\[1-9\]\|1\d\|2\[0-8\]\)\4\(\?:\(\?:1\[6-9\]\|\[2-9\]\d\)\?\d{2}\)$
现在我不再在 XML 编辑器中遇到无效的转义错误(使用 XML Spy),但我得到了这个:
invalid-escape: The given character escape is not recognized.
我已经根据此处的 XML 模式规范进行了转义: https://www.w3.org/TR/xmlschema-2/#regexs F.1.1节有一个转义表。
有人可以帮忙解决这个问题吗?
谢谢!
最佳答案
如果您检查 XSD 正则表达式语法 resources ,您会注意到不支持 non-capturing groups ((?:...)
),也不是 backreferences (\n
类似实体引用使用捕获组捕获的文本,(...)
)。
由于唯一的分隔符是 /
,因此您可以完全摆脱反向引用。
使用
((((0?[13578]|1[02])/31)/|((0?[13-9]|1[0-2])/(29|30)/))((1[6-9]|[2-9]\d)?\d{2})|(0?2/29/(((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))|(0?[1-9]|1[0-2])/(0?[1-9]|1\d|2[0-8])/(1[6-9]|[2-9]\d)?\d{2})
请注意,根据。至 regular-expressions.info :
Particularly noteworthy is the complete absence of anchors like the caret and dollar, word boundaries, and lookaround. XML schema always implicitly anchors the entire regular expression. The regex must match the whole element for the element to be considered valid.
因此,您不应在 XSD 正则表达式中使用 ^
(字符串开头)和 $
(字符串结尾)。
/
符号在正则表达式风格中被转义,它是一个正则表达式分隔符,而在 XSD 正则表达式中,没有正则表达式分隔符(因为唯一的操作是 >匹配,并且没有修饰符: XML schemas do not provide a way to specify matching modes )。因此,不要在 XSD 正则表达式中转义 /
。
在线测试仪测试注意
如果您在 regex101.com 进行测试或类似网站,请注意,在大多数情况下,如果选择 /
作为正则表达式分隔符,则需要对其进行转义。完成测试后,您可以安全地删除 /
之前的 \
。
关于regex - 如何正确转义 XSD 模式中的正则表达式模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36860613/