Yoda
Yoda

Reputation: 18068

Usage of negative lookahead causes no matches at all

I have a regex ^\/pref1\/pref2\/v.+\/(search)(\/.*)?$ it is matching for instance /pref1/pref2/v1/search/suf1/suf2.

But I want it to match anything that doesn't contain word search in that place. To achieve that I have modified regex by adding negative lookahead:

^\/pref1\/pref2\/v.+\/(?!search)(\/.*)?$

but then this for instance doesn't match:

/pref1/pref2/v1/somethingElse/suf1/suf2 but it should as somethingElse not equals search. How to fix that?

Upvotes: 2

Views: 41

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

You can use

^\/pref1\/pref2\/v[^\/]+\/(?!search(?:\/|$))[^\/]+(\/.*)?$

See the regex demo.

Details:

  • ^ - start of string
  • \/pref1\/pref2\/v - a /pref1/pref2/v string
  • [^\/]+ - one or more chars other than /
  • \/ - a / char
  • (?!search(?:\/|$)) - immediately to the right, there cannot be search string followed with / or end of string
  • [^\/]+ - one or more chars other than /
  • (\/.*)? - an optional capturing group matching a / char and then any zero or more chars other than line break chars, as many as possible
  • $ - end of string.

Upvotes: 1

Related Questions