Home > Enterprise >  Regex formation and Issue in Negation
Regex formation and Issue in Negation

Time:10-05

I need to create two regex

One, for catching these type of strings:

  • /xyz-courses/test/test
  • /abc-courses/test-abc/test-xyz
  • /abc-courses/test-abc/test-xyz?itsok=yes

But I don't want to match these strings where fixed word is prepended with -courses:

  • /fixed-courses/test/test
  • /fixed-courses/test-abc/test-xyz
  • /fixed-courses/test-abc/test-xyz?itsok=yes

I have created the following REGEX, which is working perfectly fine, but not sure about case how to exclude the prepended word fixed

/([^/] )-courses/([^/] )/([^/] )$

Second, I need to create REGEX to negate all regex created in previous step. I tried:

[^/([^/] )-courses/([^/] )/([^/] )]$

But this is showing invalid on all REGEX checkers.

CodePudding user response:

You may use this regex to disallow fixed- before courses:

^/((?!fixed-)[^/-] )-courses/([^/] )/([^/] )$

RegEx Demo

(?!fixed-) is a negative lookahead that will fail the match if fixed- appears right after / and before courses/.

For second part use this to negate first regex:

^/(?!((?!fixed-)[^/-] )-courses/([^/] )/([^/] )$). 

RegEx Demo 2

  • Related