The regex foo/(\w*)/bar
matches the string foo/123/bar
.
This is probably something basic that I've missed about regexes, but often I only want to retrieve the substring between the slashes. Is there a simple .NET API I can use without having to access the groups collection? Or an alternative way of writing the regex?
Than开发者_StackOverflow社区ks!
It is possible using lookaround:
(?<=foo/)\w*(?=/bar)
applied to foo/123/bar. matches "123". Groups are a better method and bear in mind that lookaround (in particular look behind) is not supported in all regex tools, but it is in .net.
note: \w is shorthand for a character class, you don't need to put it inside []
The short answer is no, but it really is no hassle to get the capture:
string cap = Regex.Match(inputString, @"foo/(\w*)/bar").Groups[1].ToString();
If the string is guaranteed to be matched, and you only want the substring between the two slashes, String.Split
can be used instead of Regular Expression:
String sub = str.Split('/')[1]
精彩评论