Regular expression to exclude string from match

Viewed 603

I am writing regex pattern for nginx rewrite rules to redirect the url. Here is string pattern which I would like to match and not-match.

Match url for below uri.

/abc/def  
/abc/def/#  
/abc/def#/  
/abc/def/#/  

Exclude the url if test in the string.

/abc/def/test  
/abc/def#/test  
/abc/def/#/test  
/abc/def/test/dsadasd  
/abc/def#/test/dadsd  

I have written below regex pattern but it is failing for two match highlighted in yellow

enter image description here

Any suggestions to fix this? Thanks !

1 Answers

You could use this regex pattern:

^\/abc\/def(?!.*\btest\b).*$

Demo

This regex asserts that test as a component does not appear anywhere in the path after the first two components. You could also match for \btest\b, and reject any such matches.

Related