3

I'm trying to understand the use of patterns in XSD. Hows does '+' in a pattern for a restriction work in XSD?

After some research, I found out that I can use restrictions with patterns. I do understand that the "+" means 1 or more. But will it also apply in this case?

<xsd:simpleType name="typeNumber">
        <xsd:restriction base="xsd:ID">
            <xsd:pattern value="nr[0-9]+"/>
        </xsd:restriction>
    </xsd:simpleType>

Will, for example, the value nr12345 be valid? Furthermore, I would like to know how it would be possible to make the acceptable value between nr01 and nr10.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • Should be possible to apply the XSD against some XML and observe the results.. this should be used to be able to form a more complete base question/hypothesis. – user2864740 Aug 28 '18 at 22:34
  • There are also resources on what the regular expressions are supported by patterns are allowed for XML, eg. https://www.regular-expressions.info/xml.html , http://infohost.nmt.edu/~shipman/soft/rnc/xsd-regex.html , http://www.xmlschemareference.com/regularExpression.html (searched for "xml pattern regex") – user2864740 Aug 28 '18 at 22:36
  • Matching: `nr01..nr10` is the same as matching `nr01..nr09` *or* `nr10`. Should be able to use that in conjunction with the current pattern and links above. The alternation (`|`, aka "either or") operator will be useful. – user2864740 Aug 28 '18 at 22:36
  • Frankly, if only ten values are allowed, I would be inclined to use an enumeration rather than a pattern. – Michael Kay Aug 29 '18 at 07:51

2 Answers2

2

This XSD type,

<xsd:simpleType name="typeNumber">
    <xsd:restriction base="xsd:ID">
        <xsd:pattern value="nr0[1-9]"/>
        <xsd:pattern value="nr10"/>
    </xsd:restriction>
</xsd:simpleType>

will allow nr01 through nr09 and nr10, as requested, without needing +, which, yes, does mean 1 or more occurences.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
0

You may use

<xsd:simpleType name="typeNumber">
    <xsd:restriction base="xsd:ID">
        <xsd:pattern value="nr(0?[1-9]|10)"/>
    </xsd:restriction>
</xsd:simpleType>

Details

The regex will match an entire string that matches

  • nr - nr at the start of the string
  • (0?[1-9]|10) - an optional 0 followed with a non-zero digit (see 0?[1-9] alternative) or (|) 10 value.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563