Echilon
Echilon

Reputation: 10244

Regex to ensure a specific word does not occur in the middle of a pattern

I have a regex which matches a range of characters in a list, but I'd like to prevent it from matching a word.

My Regex is:

^widget/([\w\d~]+)/?(?:[\w\d~]+)/?$

I'd like it to match like this:

Is it possible to add in a condition so it will match characters, but not if they spell the word 'add'?

Upvotes: 3

Views: 4179

Answers (1)

Phrogz
Phrogz

Reputation: 303206

^widget/(?!add)([\w\d~]+)/?(?:[\w\d~]+)/?$

This is a zero-width negative lookahead assertion; basically it says "Standing where I am right now, ensure that if I look forward I do not see the pattern add, but do not move the cursor position when I'm done."

Read up on it here: http://www.regular-expressions.info/lookaround.html

Upvotes: 9

Related Questions