Reputation: 63
Can someone explain to me how I would make a regular expression for something like this
https://clips.twitch.tv/user/ClipLink
I did this and it works fine for user but not the clip link, it only does the first letter.
https://clips.twitch.tv/(?<user>[^ ]+?)/(?<url>[^ ]+?)
If someone could post the expression that would work and explain what each part is, that would be amazing :)
Upvotes: 0
Views: 70
Reputation: 45145
Your problem here:
https://clips.twitch.tv/(?<user>[^ ]+?)/(?<url>[^ ]+?)
Is the last ?
. The ?
added to a quantifier makes the pattern lazy rather than greedy. When it's greedy it will consume as many characters as possible and only give back when it has to (to match the rest of the pattern). When it's lazy it will take as few characters as possible only expanding when it has to. Since the +
is match one or more, the least it can match is 1, so that's what it does. Removing the ?
will fix the problem.
You could also solve it by adding a $
at the end. This matches the end of the string so it would force the lazy quantifier to expand until it reached the end of the string.
As somebody else pointed out, it's a bit odd to match "not space" since there are no spaces in your url anyway. You could match [^/]
or you could just dispense with that altogether and just match with something like:
https:\/\/clips.twitch.tv\/(?<user>.+?)\/(?<url>.+)$
Or you could just use the Uri class which has properties and methods for dealing with Uri.
For example:
var uri = new Uri("https://clips.twitch.tv/user/ClipLink");
var segments = uri.Segments;
Console.WriteLine(segments[1)); // user/
Console.WriteLine(segments[2]); // ClipLink
Upvotes: 1