Jegra
Jegra

Reputation: 53

Regex to match url segment only if not preceded by specific parent segment

I'm trying to match the last segment of a url, if and only if it is not preceded by a specific segment ('news-events'). So, for example, I would like to match 'my-slug' here:

http://example.com/my-slug

...but not here:

http://example.com/news-events/my-slug

I'm working with javascript -- have tried something like this:

\b(?!news-events)(\/\w+)\b$

...but the word boundary approach doesn't work here, as the / char serves as a boundary between the segments (so, the last segment gets selected, whether or not it is preceded by 'news-events'.

Any thoughts would be appreciated.

Thanks much.

Upvotes: 5

Views: 1456

Answers (3)

user557597
user557597

Reputation:

updated for optional trailing slash


Don't be fooled, this is a tricky regex.

/^(?:(?!news-events\/[^\/\r\n]*\/?$).)*?\/([^\/\r\n]+)\/?$/

The segment is in capture group 1.

https://regex101.com/r/hrLqRq/3

 ^     
 (?:
      (?! news-events/ [^/\r\n]* /? $ )
      . 
 )*?
 / 
 ( [^/\r\n]+ )                 # (1)
 /?
 $ 

Upvotes: 3

guest271314
guest271314

Reputation: 1

You can check the .pathname or the URL for one or more words

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


let match = "/my-slug";

let not = "/news-events";

for (let src of sources) {
  let url = new URL(src);
  if (new RegExp(`^${not}${match}`).test(url.pathname)) {
    console.log("not", url.pathname)
  } else {
    if (new RegExp(`^${match}$`).test(url.pathname))
    console.log("ok", url.pathname)
  }
}

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522712

You could try splitting the URL on forward slash, and then check that the second to last entry is not news-events and the last entry is my-slug.

var url = 'http://example.com/news-events/my-slug';
var parts = url.split('/');
var n = parts.length

if (parts[n - 2] !== 'news-events' && parts[n - 1] === 'my-slug') {
    console.log("match")
}
else {
    console.log("no match")
}

Upvotes: 1

Related Questions