2011-10-12 32 views
2

我試圖在下面的字符串中找到一個字符串。使用c#查找字符串?

http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx?ID=1779 

通過使用http://example.com/TIGS/SIM/Lists字符串。我怎樣才能從它得到Team Discussion的單詞?

有時候字符串將

http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx?ID=1779 
    I need `Team Discussion` 

http://example.com/TIGS/ALIF/Lists/Artifical Lift Discussion Forum 2/DispForm.aspx?ID=8 

    I need `Artifical Lift Discussion Forum 2` 
+1

有點不同的方法;加載到'Uri'並使用'Parts'屬性。 – CodingGorilla

回答

0
路徑拉閘

如果你想看到一個正則表達式例子:

 string input = "http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx?ID=1779"; 
     string given = "http://example.com/TIGS/SIM/Lists"; 
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(given + @"\/(.+)\/"); 
     System.Text.RegularExpressions.Match match = regex.Match(input); 
     Console.WriteLine(match.Groups[1]); // Team Discussion 
0

這裏有一個簡單的方法,假設你的URL總是有相同數量的斜槓前的是你想要的:

var value = url.Split(new[]{'/'}, StringSplitOptions.RemoveEmptyEntries)[5]; 
2

如果你總是遵循這種模式,我推薦@賈斯汀的答案。然而,如果你想要一個更強大的方法,你總是可以結合System.UriPath.GetDirectoryName方法,然後執行String.Split。像this example

String url = @"http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx?ID=1779"; 
System.Uri uri = new System.Uri(url); 
String dir = Path.GetDirectoryName(uri.AbsolutePath); 
String[] parts = dir.Split(new[]{ Path.DirectorySeparatorChar }); 
Console.WriteLine(parts[parts.Length - 1]); 

唯一的主要問題,但是,你要與一個已經「編碼」(即你的空間,現在要由%20來表示)

1

該解決方案將讓你的URL的最後一個目錄不管許多目錄如何在您的網址。

string[] arr = s.Split('/'); 
string lastPart = arr[arr.Length - 2]; 

你可以這個解決方案合併成一條線,但它需要分割字符串兩次,一次爲價值觀,第二的長度。

0

這裏是另一個解決方案,它具有以下優點:

  • 不需要使用正則表達式。
  • 不需要特定的「計數」斜槓(基於特定數字的索引)。我認爲這是一個關鍵的好處,因爲如果URL的某些部分發生更改,代碼就不太可能失敗。最終,最好根據你認爲最不可能改變的文本結構的哪一部分來解析邏輯。

這種方法,然而,這依賴於以下假設,我認爲是最有可能發生變化:

  • URL必須有目標文本前右「/列表/」。
  • URL必須在目標文本後面有「/」。

基本上,我只是分割字符串的兩倍,使用的文字,我期望能夠圍繞我感興趣的區域,然後

String urlToSearch = "http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx"; 
String result = ""; 

// First, get everthing after "/Lists/" 
string[] temp1 = urlToSearch.Split(new String[] { "/Lists/" }, StringSplitOptions.RemoveEmptyEntries);     
if (temp1.Length > 1) 
{ 
    // Next, get everything before the first "/" 
    string[] temp2 = temp1[1].Split(new String[] { "/" }, StringSplitOptions.RemoveEmptyEntries); 
    result = temp2[0]; 
} 

您的答案將被保存在「結果」的變量。