Skip to content Skip to sidebar Skip to footer

Escaping Characters Within RegExp Lookbehind Assertions

At Regex to match url segment only if not preceded by specific parent segment given the input http://example.com/my-slug or http://example.com/my-slug/ the requirement is to matc

Solution 1:

Since this bit of the regular expression:

[^/]+(?=\/$|$)

matches the text y-slug (y-slug is multiple non-slash characters, optionally followed by a slash, followed by the end of the string), and y-slug is not preceded by news-events/, it’s a valid match. Since my-slug doesn’t match, it’s also the first valid match, so it’s the match that is returned.

You could add a second, positive lookbehind to indicate that any match must be a complete segment.

let re = /(?<!news-events\/)(?<=\/)[^/]+(?=\/$|$)/;

let sources = [
  "http://example.com/my-slug"
, "http://example.com/my-slug/"
, "http://example.com/news-events/my-slug"
];

for (let src of sources) {
  console.log(src.match(re))
}

Post a Comment for "Escaping Characters Within RegExp Lookbehind Assertions"