2013-01-22 161 views
-2

鑑於串正則表達式:獲取兩個斜線之間的子字符串?

http://stackoverflow.com/questions/ask/index.php 

...我想獲得第三斜線(.*?)和最後一個斜線之間的子串,即:

questions/ask 

我怎樣才能做到這一點,在C#中的正則表達式?

+0

也許看看[String.Split()](http://msdn.microsoft.com/en-us/library/b873y76a.aspx) –

回答

1
Uri url = new Uri("http://stackoverflow.com/questions/ask/index.php"); 
string s = string.Join("", url.Segments.Take(url.Segments.Length - 1)).Trim('/'); 
+0

這將在開頭有一個額外的'/',但看起來不錯。 – SwDevMan81

+0

你必須'.Trim('/')'來獲得OP所要求的。 –

+0

愛你= *謝謝 – lnnahdbandninja

0

嘗試使用現有的Uri和Path類而不是字符串匹配和正則表達式。喜歡的東西:

Path.GetDirectoryName(new Uri(url).AbsolutePath) 
+0

只有正則表達式需要= \ – lnnahdbandninja

+1

@lnnahdbandninja現在你有兩個問題。 – Servy

+0

@lnnahdbandninja,如果現有測試代碼已經存在,那麼推出自己的Url自定義分析並不是一個好主意 - 使用分段的答案比單獨使用正則表達式要安全得多... –

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 
+0

對於分段,完全符合人們需要刪除第一個和最後一個段而不是硬編碼1和2的問題(即根據問題應該產生「http://www.contoso.com/title/foo/bar/index.htm」) 「title/foo/bar」這是3段) –

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

正確的方式做這將是使用Uri對象。

Uri u = new Uri("http://stackoverflow.com/questions/ask/index.php"); 
string[] s = u.Segments; 
0

其他答案是要走的路。但是,如果你還在尋找正則表達式這個應該工作:

([^/]*/[^/]*)/[^/]*$ 

你正在尋找的路徑是在第一個子匹配。

相關問題