模式验证中的正则表达式

Regular Expression in schema validation

我需要一个 xml 模式,它验证一个空节点和一个具有 8 位数字的节点为真。所以我用以下简单类型定义了一个 XML-Schema:

<xs:simpleType name="LeererStringOder8Zeichen">
    <xs:restriction base="xs:string">
        <xs:pattern value="(^$|\d{8})"/>
    </xs:restriction>
</xs:simpleType>

我已经使用 java.util.regex 和来自 Xerces 的内部 RegularExpression-class 尝试了这个正则表达式。两者都返回 true。但是当我在我的 WS 中使用这个 simpleType 时(使用 CXF 实现),当我提交一个空字符串(例如 )时,我得到一个验证错误。为什么?有人知道如何更改我的架构以使其接受一个空标签和一个包含 8 位数字的标签吗?

感谢帮助, 安德烈亚斯

这会起作用:

<xs:simpleType name="LeererStringOder8Zeichen">
    <xs:restriction base="xs:string">
        <xs:pattern value="|\d{8}"/>
    </xs:restriction>
</xs:simpleType>

|\d{8} 表示不匹配或匹配八位数字。 (您也可以使用 |[0-9]{8}。)

看来 (^$|\d{8})(虽然我认为你的意思是 ^(|\d{8})$)不起作用的原因是 XML Schema Regular Expressions page 声明:

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.

所以您的锚点显然导致正则表达式无法按预期运行。

正如@dbank 指出的那样,XSD 中的正则表达式是隐式锚定的,$ 和 ^ 符号不被识别为元字符。然而,一些 XSD "implementations"(所谓的)忽略了这里的规范,只是将所有正则表达式处理委托给一些不知道 XSD 规则的底层库。

我自己选择的匹配零长度字符串或恰好 8 位数字的正则表达式是 (\d{8})?