XSD正则表达式模式:这个或者什么都没有

时间:2010-11-19 16:58:53

标签: regex xsd xsd-validation

我正在尝试在XSD中定义一个方案规则,其中一个字符串长度为8个字符:

<PostedDate>42183296</PostedDate>

也允许填空:

<PostedDate>        </PostedDate>

让我进入了XSD:

<xs:simpleType name="DateFormat">
   <xs:restriction base="xs:string">
      <xs:length value="8" />            //exactly 8 characters long
</xs:simpleType>

但值 也可以为空(即零个字符长):

<PostedDate></PostedDate>
<PostedDate />

这让我天真地尝试:

<xs:simpleType name="DateFormat">
   <xs:restriction base="xs:string">
      <xs:length value="8" />            //exactly 8 characters long
      <xs:length value="0" />            //exactly 0 characters long
</xs:simpleType>

当然不允许这样做。

与XSD中的情况一样,大多数格式都无法使用XSD轻松表示,因此我选择尝试使用正则表达式规则:

.{8} | ""

尝试转换为XSD我输入:

<xs:simpleType name="DateFormat">
    <xs:restriction base="xs:string">
        <xs:pattern value=".{8}|''" />
    </xs:restriction>
</xs:simpleType>

但它不起作用:

''20101111' is not facet-valid with respect to pattern '.{8}|''' for type 'DateFormat'

我也试过

  • <xs:pattern value="[0-9]{8}|''" />
  • <xs:pattern value="([0-9]{8})|('')" />
  • <xs:pattern value="(\d{8})|('')" />

其他任何一种模式都可以解决问题   - 一些特定的模式   - 空

加分:任何人都可以指向the XSD documentation\d匹配数字的地方吗?或者其他特殊模式代码是什么?

2 个答案:

答案 0 :(得分:11)

我可能会猜测,模式应该看起来像\d{8}|,这意味着“八位数字或什么都没有”,但不是八位数或两位数。但是,这并不能解释为什么20101111不匹配。您确定元素值中没有空格或其他符号吗?
据说\d匹配“F.1.1 Character Class Escapes”部分中的数字

答案 1 :(得分:3)

我也在同样的情况下允许空字符串,否则它必须是6个长度数字。最后我使用了以下内容。这对我有用

<xs:simpleType name="DateFormat">
    <xs:restriction base="xs:string">
        <xs:pattern value="|[0-9]{8}" />
    </xs:restriction>
</xs:simpleType>
相关问题