Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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:

  • widget/JQYHHU - View widget, should match
  • widget/JQYHHU/ - View widget, should match
  • widget/JQYHHU/bag-of-screws - View widget, should match
  • widget/JQYHHU/bag-of-screws/ - View widget, should match
  • widget/add - View widget, should not match
  • widget/add/ - View widget, should not match

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

like image 792
Echilon Avatar asked Jan 18 '26 21:01

Echilon


1 Answers

^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

like image 51
Phrogz Avatar answered Jan 23 '26 07:01

Phrogz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!