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

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



Solution 1:[1]

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\/?$

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Artyom Vancyan
Solution 2