Regex to match a URL segment, unless preceded by a specific parent segment

I am 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 map "my-slug" here:

http://example.com/my-slug 

... but not here:

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

I work with javascript - tried something like this:

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

... but the word boundary approach does not work here, since / char serves as the boundary between segments (therefore, the last segment is selected, regardless of whether it is preceded by "news events".

Any thoughts would be appreciated.

Thank you very much.

+5
source share
3 answers

updated for extra slash


Do not be fooled, this is a complex regular expression.

/^(?:(?!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) /? $ 
+3
source

You can try splitting the url and then check that the second-last entry is not news-events , but the last my-slug entry.

 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") } 
+1
source

You can check the .pathname or 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) } } 
+1
source

Source: https://habr.com/ru/post/1272681/


All Articles