给出字符串
http://stackoverflow.com/questions/ask/index.php
...我想获得第3个斜杠(.*?)
和最后一个斜杠之间的子串,即:
questions/ask
如何使用C#中的正则表达式实现此目的?
答案 0 :(得分:2)
您可以查看Uri.Segments
属性
Uri uriAddress1 = new Uri("http://www.contoso.com/title/index.htm");
Console.WriteLine("The parts are {0}, {1}, {2}", uriAddress1.Segments[0],
uriAddress1.Segments[1], uriAddress1.Segments[2]);
产生以下输出:
The parts are /, title/, index.htm
答案 1 :(得分:2)
Uri uri = new Uri("http://stackoverflow.com/questions/ask/index.php");
string result = uri.Segments[1] + uri.Segments[2];
result = result.Remove(result.Length - 1);
Console.WriteLine(result);
答案 2 :(得分:1)
Uri url = new Uri("http://stackoverflow.com/questions/ask/index.php");
string s = string.Join("", url.Segments.Take(url.Segments.Length - 1)).Trim('/');
答案 3 :(得分:0)
尝试使用现有的Uri和Path类,而不是字符串匹配和正则表达式。类似的东西:
Path.GetDirectoryName(new Uri(url).AbsolutePath)
答案 4 :(得分:0)
执行此操作的正确方法是使用Uri对象。
Uri u = new Uri("http://stackoverflow.com/questions/ask/index.php");
string[] s = u.Segments;
答案 5 :(得分:0)
其他答案是要走的路。但是,如果你仍在寻找正则表达式,那么这个应该可行:
([^/]*/[^/]*)/[^/]*$
您要查找的路径位于第一个子匹配中。