Regex for matching string between a keyword and last occurance of a character

Viewed 34

I'm very rusty with regex right now so I'll illustrate my problem with an example:

//url/fb9ceb12-1492-4b01-b951-30e848f3adbc/fb9c2b12-1496-4r01-b92b-30e848f3adbc/keyword/.....

I'm trying to match the text in italics i.e. the string betweeen the /keyword and the / preceeding it. So far my I have managed to achieve this regex:

(?!\/)()(?!\/keyword)(.*)(?=\/)

Which unfortunately yields the entire string //url/fb9ceb12-1492-4b01-b951-30e848f3adbc/fb9c2b12-1496-4r01-b92b-30e848f3adbc/ before /keyword/ and not fb9c2b12-1496-4r01-b92b-30e848f3adbc.

Any help would be appreciated!

1 Answers

You can use

/[^\/]+(?=\/keyword\/)/

See the regex demo. Details:

  • [^\/]+ - one or more chars other than /
  • (?=\/keyword\/) - a positive lookahead that requires /keyword/ substring to appear immediately to the right of the current location.

See the JavaScript demo:

const regex = /[^\/]+(?=\/keyword\/)/;
const text = '//url/fb9ceb12-1492-4b01-b951-30e848f3adbc/fb9c2b12-1496-4r01-b92b-30e848f3adbc/keyword/.....';
console.log(text.match(regex));

Related