Regex to ignore string in URL

665 Views Asked by At

Trying to write regex for reddits subreddits. My regex will replace the subreddit name with a link, but I would like for it to ignore a link within a url that's already being displayed. For example let's say I have the following 3 strings.

https://www.reddit.com/r/starwars/comments/12345

/r/starwars

r/starwars

I'm trying to write regex that will match the bottom 2 strings but ignore the top one. I'm attempting to use regex LookBehind but haven't been able to get it to work. My current regex is:

(?<=[^m])\/?r\/([a-zA-Z_])+

I would have thought the ^m would ignore any string starting with the 'm' from the '.com'

1

There are 1 best solutions below

1
On BEST ANSWER

You shouldn't need look-behind or anything fancy for this. Instead, use the ^ and $ (the beginning- and end-of-string operators). Try a regex like:

var pattern = /^\/?r\/[A-Za-z_]+$/;
pattern.test('https://www.reddit.com/r/starwars/comments/12345'); // false
pattern.test('/r/starwars/comments/12345'); // false
pattern.test('/r/starwars'); // true
pattern.test('r/starwars'); // true