http://stackoverflow.com/questions/ask/index.php
...我想獲得第三斜線(.*?)
和最後一個斜線之間的子串,即:
questions/ask
我怎樣才能做到這一點,在C#中的正則表達式?
http://stackoverflow.com/questions/ask/index.php
...我想獲得第三斜線(.*?)
和最後一個斜線之間的子串,即:
questions/ask
我怎樣才能做到這一點,在C#中的正則表達式?
Uri url = new Uri("http://stackoverflow.com/questions/ask/index.php");
string s = string.Join("", url.Segments.Take(url.Segments.Length - 1)).Trim('/');
嘗試使用現有的Uri和Path類而不是字符串匹配和正則表達式。喜歡的東西:
Path.GetDirectoryName(new Uri(url).AbsolutePath)
只有正則表達式需要= \ – lnnahdbandninja
@lnnahdbandninja現在你有兩個問題。 – Servy
@lnnahdbandninja,如果現有測試代碼已經存在,那麼推出自己的Url自定義分析並不是一個好主意 - 使用分段的答案比單獨使用正則表達式要安全得多... –
你可以看一下在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的問題(即根據問題應該產生「http://www.contoso.com/title/foo/bar/index.htm」) 「title/foo/bar」這是3段) –
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);
正確的方式做這將是使用Uri對象。
Uri u = new Uri("http://stackoverflow.com/questions/ask/index.php");
string[] s = u.Segments;
其他答案是要走的路。但是,如果你還在尋找正則表達式這個應該工作:
([^/]*/[^/]*)/[^/]*$
你正在尋找的路徑是在第一個子匹配。
也許看看[String.Split()](http://msdn.microsoft.com/en-us/library/b873y76a.aspx) –