Kundan Pandit
Kundan Pandit

Reputation: 412

Regex to match any words except words with given pattern

I want to match all words except following words :

1) any-random-word 
2) any-random-word/ 
3) any-random-word/123 
4) any-random-word/abcdef

so that following similar words can be matched.

1) any-random-word123
2) any-random-word(any non-word character other than '/')123
2) any-random-wordabcdef
4) any-random-word(any non-word character other than '/')abcdef

In fact any number or any word can be appened after 'any-random-word/'.

I tried with

^(?!any-random-word(\/?)(\w+)$|any-random-word$)

but its escaping all words having any-random-word in it.

Thanks.

Upvotes: 0

Views: 1336

Answers (1)

Jerry
Jerry

Reputation: 71538

You can change your current regex a little:

^(?!.*\bany-random-word\b)

And if you want to actually match something, add .+ at the end:

^(?!.*\bany-random-word\b).+

regex101 demo

\b (a word boundary) ensures that there's no other \w character around the word you don't want to match.


Edit: As per your further clarification, I would suggest this regex:

^(?!.*\bany-random-word(?:/|$)).+

The main part of the regex is the negative lookahead: (?!.*\bany-random-word(?:/|$)). It will cause the whole match to fail if what's inside matches.

.*\bany-random-word(?:/|$) will match any-random-word at the end of a string or followed by /, anywhere in the string that it is being tested against.

So, if you have any-random-word/, it will match, and cause the whole match to fail. If you have the string ending in any-random-word, again, the whole match will fail.

Upvotes: 1

Related Questions