限制 XSD 中的字符串,使它们没有前导或尾随空格并且只包含字母数字、连字符和下划线?

Restrict strings in XSD so they don't have leading or trailing whitespace and only contain alphanumerics, hyphen and an underscore?

我正在尝试消除 leading/trailing 空格,还想确保我的字符串不包含特殊字符(“-”和“_”除外,我需要这些字符)。从另一个 post 我想出了这个

<xs:simpleType name="RandomString"> 
    <xs:restriction base="xs:string">
      <xs:pattern value="\S([a-zA-Z0-9_-]*\S)?"/> 
    </xs:restriction>
 </xs:simpleType>

到目前为止,我已经找到了一种方法来不允许前导空格、尾随空格和多个特殊字符。但是,我有这种独特的情况,它允许任何一个特殊字符接近字符串的末尾

abcdef1234!@#abc123!xyz 这样的字符串根据正则表达式是不允许的,但是像 abc123!random234@ 这样的字符串(只有一个特殊字符结束字符串)没有被我的正则表达式捕获。我错过了什么吗?

您的正则表达式匹配不受欢迎的字符串,因为 \S 匹配 任何 非空白字符。

您的 [a-zA-Z0-9_-] 字符 class 不匹配空格,因此您可以完全省略 \S 模式并使用

<xs:pattern value="[a-zA-Z0-9_-]+"/>

参见regex demo