XML Regex - Negative match

那年仲夏 提交于 2020-07-08 22:46:30

问题


I have a problem with negative lookahead in XSD pattern. When I specified:

<xs:pattern value="^(?!(00|\+\d))\d{6,}$"/>

then I got an error message:

Value '^(?!(00|\+\d))\d{6,}$' is not a valid XML regular expression.

Any idea why it does not work?

In online javascript validator it works fine (e.g. here under unit tests section click on "run test").

I need to validate phone numbers. The phone number cannot include international prefixes (+\d) and (00).

Thanks


回答1:


Try the following regex:

[1-9][0-9]{5,} | 0[1-9][0-9]{4,}

This matches a number which does not begin with zero and is followed by any digit (including zero) 5 or more times, and it also matches a number which starts with zero and is not immediately followed by zero, but after that can have 0-9.




回答2:


I will add my deleted comment as an answer:

([1-9][0-9]|[0-9][1-9])[0-9]{4,}

See the regex demo.

The regex should work well for your scenario because

  • ([1-9][0-9]|[0-9][1-9]) - matches either 1 digit from 1-9 ranges and any digit after or (|) any 1 digit followed with any digit but 0 - making up 2 digits
  • [0-9]{4,} - matches 4 and more any digits.

This pattern only matches a full/entire string because all regex patterns inside XSD pattern are anchored by default (so, you do not have to and can't enclose the pattern with ^ and $).

Right, there is no lookaround support in XSD regex (no lookaheads, nor lookbehinds). Besides, XSD regex has other interesting limitations/features:

  • ^ and $ anchors
  • Non-capturing groups like (?:...) (use capturing ones instead)
  • / should not be escaped, do not use \/
  • \d should be written as [0-9] to only match ASCII digits (same as in .NET)
  • Back-references like \1, \2 are not supported.
  • No word boundaries are supported either.

See some more XSD regex description at regular-expressions.info.



来源:https://stackoverflow.com/questions/38436165/xml-regex-negative-match

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!