Regular expression match numbers not starting with string

Viewed 75

I came up with a need in a regular expression for finding numbers that do not start with COM. I tried the following expression, but it does not work as expected, and the condition for COM does not work.

(?!(COM|СОМ))\d{11,19}

https://regex101.com/r/Ap628q/1/

1 Answers

You need a negative lookbehind to check if a string is not immediately preceded with some other pattern. Also, since you are matching a range of digits, you should include digit boundaries, (?<!\d) and (?!\d), to your regex.

Use

(?<!COM|\d)\d{11,19}(?!\d)
(?<!COM)(?<!\d)\d{11,19}(?!\d)

See the regex demo. The latter will work with Python and Boost regex libraries that require the lookbehind alternatives to match the text of the same length.

Details

  • (?<!COM) - a negative lookbehind that fails the match if there is COM immediately to the left of the current location
  • (?<!\d) - a negative lookbehind that fails the match if there is as digit immediately to the left of the current location
  • \d{11,19} - eleven to nineteen digits
  • (?!\d) - a negative lookahead that fails the match if there is as digit immediately to the right of the current location.
Related