xml schema check fail with pattern match

Viewed 39

i have such boilerplate code in xsd schema.

      <xs:attribute name="version" use="required">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="1.1"/>
            <xs:enumeration value="1.2"/>
            <xs:enumeration value="1.3"/>
            <xs:enumeration value="1.4"/>
            <xs:enumeration value="1.5"/>
            <xs:enumeration value="1.6"/>
            <xs:enumeration value="1.7"/>
            <xs:enumeration value="1.8"/>
            <xs:enumeration value="1.9"/>
            <xs:enumeration value="1.10"/>
            <xs:enumeration value="1.11"/>
            <xs:enumeration value="1.12"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>

that I simply want to replace with pattern as follows.

<xs:pattern value="1.[1-9]|[1-1][0-2]"/>

it passes the 1.2 or 1.6 but fails with "1.10". with lxml.etree.DocumentInvalid: Element 'sfd', attribute 'version': [facet 'pattern'] The value '1.10' is not accepted by the pattern '1.[1-9]|[1-1][0-2]'

I thought [1-9]|[1-1][0-2] represents the range between 1-9 and 10-12.

what is the problem?

2 Answers

Your regex (see its demo) matches a string that either

  • 1.[1-9] - starts with 1, then has any char other than a line break char and the a digit from 1 to 9
  • | - or
  • [1-1][0-2] - starts with 1 (note [1-1] = 1) and then a digit from 0 to 2.

You may use

<xs:pattern value="1\.(1[0-2]|[1-9])"/>

See the regex demo. Bearing in mind that XSD schema regex pattern must match the entire string, here is what it matches:

  • 1 - matches 1
  • \. - matches a literal dot (. without an escape symbol matches any char but a line break char)
  • (1[0-2]|[1-9]) - a capturing group (note XSD Schema regex does not support non-capturing ones) matching 10, 11, 12 or a digit from 1 to 9 range.

Try parentheses:

<xs:pattern value="1\.([1-9]|1[0-2])"/>

Note the escaped ".", otherwise you will match things like 1$12. And I think [1-1] is probably allowed, but 1 seems simpler.

Related