如果需要非空元素,为什么要使用正则表达式?

Why use a regex if you need an nonempty element?

我需要指定某些 XML 元素始终不为空且不为空。我发现 this question,它建议使用限制将 minLength 设置为 1。但是一些张贴者建议使用带有正则表达式的模式限制来代替 minLength 或除 minLength 之外限制。正则表达式相对于 minLength 的优势是什么?

使用正则表达式可以在指定有效性时区分空白字符和非空白字符,而不是单独依赖长度。

例如,没有正则表达式,NonEmptyString

<xs:simpleType name="NonEmptyString">
  <xs:restriction base="xs:string">
    <xs:minLength value="1" />
  </xs:restriction>
</xs:simpleType>

允许<x> </x>(但不允许<x/><x></x>)。 这可能是您想要的,也可能不是您想要的。

同时,使用正则表达式,NonEmptyStringWithoutSpaces

<xs:simpleType name="NonEmptyStringWithoutSpaces">
   <xs:restriction base="xs:string">
      <xs:pattern value="\S+"/>  <!-- one or more non-whitespace chars -->
   </xs:restriction>
</xs:simpleType>

不会允许<x> </x>(并且仍然不允许<x/><x></x>)。但是请注意,这也不允许 <x>A B</x>这可能不是你想要的。

如果您想允许嵌入空格,您可以使用

<xs:simpleType name="NonEmptyNonBlankString">
   <xs:restriction base="xs:string">
      <xs:pattern value=".*\S.*"/>  <!-- at least one non-whitespace char -->
   </xs:restriction>
</xs:simpleType>

允许<x> </x><x/><x></x>,同时允许<x>A B</x><x> A </x> .或者,如果没有正则表达式,您可以使用 xs:whiteSpace 方面:

<xs:simpleType name="NonEmptyNonBlankString">
   <xs:restriction base="xs:string">
    <xs:minLength value="1" />
    <xs:whiteSpace value='collapse'/>
   </xs:restriction>
</xs:simpleType>

这大概就是你想要的。