Regular Expression Negative Match

I have a problem with regex, I try to ignore only the number "41", I want all 4, 1, 14, etc. corresponded.

I have this [^\b41\b] , which is really what I want, but it also ignores all single iterations of values ​​1 and 4.

As an example, this matches "41", but I want it to not match: \ B41 \ b p>

+4
source share
3 answers

Try something like:

 \b(?!41\b)(\d+) 

The construction (?!...) is a negative scan , so this means: find the word boundary that does not follow "41" and capture the sequence of numbers after it.

+5
source

You can use a negative predictive statement to exclude 41 :

 /\b(?!41\b)\d+\b/ 

This regular expression should be interpreted as: on any boundary of the word \b , if it is not followed by 41\b ( (?!41\b) ), match one or more digits followed by the boundary of the word.

Or the same with a negative look-behind expression:

 /\b\d+\b(?<!\b41)/ 

This regular expression should be interpreted as: match one or more numbers that are surrounded by word boundaries, but only if the substring at the end of the match is not preceded by \b41 ( (?<!\b41) ).

Or it may even use only the basic syntax:

 /\b(\d|[0-35-9]\d|\d[02-9]|\d{3,})\b/ 

This corresponds only to sequences of numbers surrounded by word boundaries:

  • one digit
  • two digits not having 4 in the first position or not 1 in the second position
  • three or more digits
+1
source

This is similar to the question " Regular expression that does not contain a specific string , so I will repeat my answer from there:

 ^((?!41).)*$ 

This will work for an arbitrary string, not just 41. See my answer there for an explanation.

+1
source

Source: https://habr.com/ru/post/1305107/


All Articles