Home > database >  regex match only if there is one occurence of string and it's the last occurence
regex match only if there is one occurence of string and it's the last occurence

Time:05-06

Hopefully the title made sense

My current regex is this .phone.*.telephoneNumber\/?$. I'm trying to match json paths and paths would look like this

  1. /phone/0/telephoneNumber - should match
  2. /phone/0/telephoneNumber/telephoneNumber - should not match

With my current regex this both matches

I need that .* 0 or more any character before telephone number because there could be anything after /phone/.. and i'm trying to look for matches where it ends with telephoneNumber only if it's not followed by another /telephoneNumber

CodePudding user response:

0 or more any character before the telephone number.

If you meant the count of characters could be 0 or more then use this

\/phone\/(?:\w \/)?telephoneNumber\/?$

If you meant that it should be a number greater than 0 then use this

\/phone\/\d \/telephoneNumber\/?$

CodePudding user response:

if telephoneNumber is a literal string then you can use a negative lookahead to make sure that it is not in between phone/ and /telephoneNumber.

\/phone\/0\/((?!telephoneNumber).)*telephoneNumber$

matches /phone/0/telephoneNumber
does not match /phone/0/telephoneNumber/telephoneNumber

Warning this matches /phone/0/telephonenumber/telephoneNumber unless we use the option /i case insensitive.
The full regex is therefore

/\/phone\/0\/((?!telephoneNumber).)*telephoneNumber$/gmi

see https://regex101.com/r/1WEF3U/1

  • Related