简体   繁体   中英

Regex trouble: how to get everything between the last two forward slashes

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?

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 (*$)

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();

Try this http://regexr.com?38c43

(?:[az/]+)/([az]+)

Look in the first (and only) group, it'll have the last item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM