-2

I want to get the handle out of a YouTube channel url.

The url usually like this: https://www.youtube.com/@ChannelHandle

I want to get only the handle, so I come up with this regex : /(?<=\/@).*.(?=\/|$|)/

My problem is that it stops at the end of the url, but it doesn't stop at /

How to stop either at / or string end?

Feralheart
  • 1,881
  • 5
  • 28
  • 59

1 Answers1

-1

You have an extra | in your alternatives at the end, so the lookahead matches an empty string anywhere.

You should also use a non-greedy quantifier so it stops at either / or the end of the string, whichever comes first. A greedy quantifier will keep going until the last match of the lookahead.

/(?<=\/@).+?(?=\/|$)/

But a simpler way is just to match a sequence of characters not including /:

/(?<=\/@)[^/]+/
Barmar
  • 741,623
  • 53
  • 500
  • 612