Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match any number except 0 and 1 consisting of max four digits

Tags:

regex

I tried the following to match any number except 0 and 1 (say, 2 to 9999), but it does not seem to work as desired.

\d[0-9]?[0-9]?[^0-1]*
like image 823
Anand Avatar asked Sep 18 '25 12:09

Anand


1 Answers

You can match all numbers from 2 to 9999 using

\b(?![01]\b)\d{1,4}\b

Or (if you have individual strings)

^(?![01]$)\d{1,4}$ 

See demo

The (?!...) is a negative lookahead that is used here to define exceptions.

More details

  • \b - word boundary (if ^ is used - start of the string)
  • (?![01]\b) - a negative lookahead that fails the match if there is 0 or 1 ([01] is a character class that matches a single char from the set defined in the class) as a whole word (or string if $ is used instead of \b)
  • \d{1,4} - 1, 2, 3 or 4 digits
  • \b - a trailing word boundary (no digit, letter or _ can appear immediately to the right, if there can be a letter or _, replace with (?!\d)).
like image 158
Wiktor Stribiżew Avatar answered Sep 21 '25 02:09

Wiktor Stribiżew