Reputation: 10474
I have a string with a variable amount of backslashes. Now I want to collect only the part (letters) between the last two backslashes.
So if I have /this/is/a/string/blablablablabla
I want to capture string
and if I have /this/is/a/longer/string/than/the/one/before/baba
I want to capture before
.
What I have tried is:
Regex.Match(myString, @"/(.*)/.*$").Groups[0].Value
but this captures everything between the first slash and also things after the last, and I want it to be between the one-before-last till the last. I am quite new to regexes and hope someone can help me out.
The last answer of leon is/([^/]*)/[^/]*$
, but this captures everything after the last / as well, and also includes the first /
.
How can I fix this?
Upvotes: 0
Views: 2530
Reputation: 9644
If there is only one such pattern in your string, you can just use
/(\w+)/[^/]*$
Your data is in the first captured group.
[^/]
will match anything BUT /
, \w
is short for [0-9a-zA-Z_]
.
EDIT: Comment from OP
Groups[1]
was the first capturing group. So the answer in C# was:
answer = Regex.Match(myString, @"/(\w+)/[^/]*$").Groups[1].Value;
Let's go through it: /
states we match the /
, then we capture with (\w+)
one or more words and we stop at a /
. Then we do not match the slash itself with [^/]
and we match everything till the end (*$)
Upvotes: 3
Reputation: 5402
A direct answer to your question would be:
/([^/]*)/[^/]*$
Or, since your strings are pretty straightforward, you can avoid regexes altogether:
if (input.EndsWith("/"))
return input.Split('/').Last();
else
return input.Split('/').Reverse().Skip(1).First();
Upvotes: 1
Reputation: 2824
Try this http://regexr.com?38c43
(?:[a-z/]+)/([a-z]+)
Look in the first (and only) group, it'll have the last item.
Upvotes: 0