简体   繁体   中英

Regular Expression in schema validation

I need an xml schema, which validates an empty node and a node with 8 digits to true. So I defined an XML-Schema with the following simple type:

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

I have tried this regular expression using java.util.regex and the internal RegularExpression-class from Xerces. Both returned true. But when I use this simpleType in my WS (implemented using CXF), I get a validation error, when I submit an empty string (eg ). Why? Has anybody an idea, how to change my schema that it accepts an empty tag and a tag containing 8 digits?

Thank for help, Andreas

This will work:

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

|\\d{8} means match nothing or eight digits. (You could also use |[0-9]{8} .)

It seems the reason (^$|\\d{8}) (although I think you meant something like ^(|\\d{8})$ ) doesn't work is because of what this XML Schema Regular Expressions page states:

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.

So your anchors were apparently causing the regex to not operate as desired.

As @dbank points out, regular expressions in XSD are implicitly anchored and the $ and ^ symbols are not recognized as meta-characters. However, some XSD "implementations" (so-called) have ignored the spec here, and simply delegate all regex processing to some underlying library which doesn't know about the XSD rules.

My own choice for a regular expression that matches either a zero-length string, or exactly 8 digits, would be (\\d{8})?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM