Jeparov
Jeparov

Reputation: 165

Match all except certain phrase

I found a numerous questions regard to "matching all except a single word in string". However, none of them do not work in case of phrase (two or more words combined). Suppose I have a string as in example (RegEx). I want to match all possible combination of a single word + 10-digits number except of certain combination/phrase "nip + 10-digits number" (+ means a simple space). In my example I use \bnip\s*\d{10}\b to match "nip + 10-digits number" but I want to match all extept "nip + 10-digits number". hello should not be matched too because of lack of 10-digits number on the right side. Would be appreciated for any help.
Example:

   hello 
   alpha 1111111111 # should be matched
   allla 2322322321 # should be matched
   nip 5260305006 
   pin 5260305006 # should be matched
   nipp 5260305006 # should be matched

Upvotes: 2

Views: 897

Answers (1)

The fourth bird
The fourth bird

Reputation: 163467

You might use

 \b(?!nip\b)\S+\s*\d{10}\b

Explanation

  • \b(?!nip\b) A word boundary, assert what is directly to the right is not nip and a word boundary
  • \S+\s* Match 1+ non whitespace chars followed by optional whitespace chars (Or use \w+ instead of \S+ to match only word chars)
  • \d{10}\b Match 10 digits followed by a word boundary

Regex demo

If you want to want to match all possible combination of a single word + 10-digits and don't want to match nip + 10-digits number" (+ means a simple space) you can exclude that from the match including the space and the 10 digits.

Note that this does match nip5260305006 as there is no space in between.

\b(?!nip \d{10}\b)\S+\s*\d{10}\b

Regex demo

Upvotes: 3

Related Questions