使用xjc(ant)和jaxb验证在xsd中使用正则表达式反斜杠

时间:2010-06-27 23:10:25

标签: regex validation xsd jaxb xjc

我的xsd文件中有以下正则表达式:

<xsd:simpleType name="Host">
    <xsd:restriction base="xsd:string">
        <xsd:pattern
            value="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b">
        </xsd:pattern>
    </xsd:restriction>
</xsd:simpleType>

当通过xjc从ant生成时,我得到以下异常:

  [xjc] [ERROR] InvalidRegex: Pattern value '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b' is not a valid regular expression. The reported error was: 'This expression is not supported in the current option setting.' at column '2'.
  [xjc]   line 10 of file:/.../src/META-INF/portscan.xsd

我可以通过将每个反斜杠()更改为双反斜杠(\)来解决这个问题:

<xsd:simpleType name="Host">
    <xsd:restriction base="xsd:string">
        <xsd:pattern
            value="\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b">
        </xsd:pattern>
    </xsd:restriction>
</xsd:simpleType>

但是,当在编组期间运行验证时,我得到以下异常:

Caused by - class org.xml.sax.SAXParseException: cvc-pattern-valid: Value '80.245.120.45' is not facet-valid with respect to pattern '\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b' for type 'Host'.

显然,双反斜杠(\\)负责验证失败。但是,如何编写单反斜杠以使xjc正常工作?

编辑:

好吧,现在找到答案,好像在xjc regexp中支持“\ b”。让它们解决问题,它现在生成没有错误,似乎在运行时工作。好极了! :)

虽然有人知道这是否安全没有字界限?也许有另一种选择?

1 个答案:

答案 0 :(得分:0)

XML Schema规范中定义的正则表达式风格不支持单词边界。

在您的情况下,不需要单词边界。 XML模式类型中的模式构面始终要求正则表达式匹配整个字符串,就好像正则表达式以字符串开始的锚^\A开头并以字符串结尾结束锚$\z。由于XML模式正则表达式始终与整个字符串匹配,因此您无法在正则表达式中使用这些锚点。

相关问题