2010-10-21 133 views
3

在C#中,如何使用正則表達式找到以'$'開頭並以空格結尾的所有單詞,長字符串?

回答

8

嘗試:

var matches = Regex.Matches(input, "(\\$\\w+) "); 

在上面,\\w匹配單詞字符。如果我是正確的,這些是A-Z,a-z和 - 。如果你想匹配所有不是空間的東西,你可以使用\\S。如果你想要一個特定的集合,可以通過例如[a-zA-Z0-9]

圍繞(\\$\\w+)的方括號確保了特定匹配的結果matches[0].Groups[1].Value;給出了backets內部的值(因此排除了尾部空格)。

作爲一個完整的例子:

string input = "$a1 $a2 $b1 $b2"; 

foreach (Match match in Regex.Matches(input, "(\\$\\w+) ")) 
{ 
    Console.WriteLine(match.Groups[1].Value); 
} 

這將產生以下輸出:

$a1 
$a2 
$b1 

的$ b2爲當然省略,因爲它不具有結尾間隔。

+0

感謝您的快速回復,但這隻返回我的最後一場比賽從字符串中,我想獲得所有的匹配。 – 2010-10-21 12:10:11

+1

我用一個例子來說明答案。我不明白爲什麼這不會返回您的輸入測試中的所有項目。你能否提供一個只返回最後一場比賽的例子輸入? – 2010-10-21 12:13:32

+0

對不起,你的正則表達式工作完全沒問題,實際上我沒有循環遍歷每一場比賽,我使用你的代碼匹配[0] .Groups [1] .Value;我只得到一場比賽。看到下面的代碼,它正常工作,並返回所有匹配。在下一條評論中添加代碼。 – 2010-10-21 12:58:35

0
var a1 = "fdjksf $jgjkd $hfj".Split(" ".ToCharArray()) 
            .ToList() 
            .Where(X=>Regex.Match(X , "(\\$[a-zA-Z]*)").Success); 
+0

感謝您的快速回復,但是這隻會返回一個字符串的最後一場比賽,我想要獲得所有比賽。 – 2010-10-21 12:12:29

+0

編輯於...... – 2010-10-21 12:38:54

3

您可以嘗試一下沒有正則表達式,這可能會更快。

string longText = ""; 
    List<string> found = new List<string>(); 
    foreach (var item in longText.Split(' ')) 
    { 
     if (item.StartsWith("$")) 
     { 
      found.Add(item); 
     } 
    } 

編輯: Zain公司謝赫的評論後,我寫了一個簡單的程序,以基準,在這裏不用的結果。

 string input = "$a1 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2 $a2 $b1 $b2"; 
     var s1 = Stopwatch.StartNew(); 
     double first; 
     foreach (Match match in Regex.Matches(input, "(\\$\\w+) ")) 
     { 
     } 
     s1.Stop(); 
     Console.WriteLine(" 1) " + (s1.Elapsed.TotalMilliseconds * 1000 * 1000).ToString("0.00 ns")); 
     first = s1.Elapsed.TotalMilliseconds; 
     s1.Reset(); 

     s1 = Stopwatch.StartNew(); 

     foreach (var item in input.Split(' ')) 
     { 
      if (item.StartsWith("$")) 
      { 
      } 
     } 
     s1.Stop(); 
     Console.WriteLine(" 2) " + (s1.Elapsed.TotalMilliseconds * 1000 * 1000).ToString("0.00 ns")); 
     Console.WriteLine(s1.Elapsed.TotalMilliseconds - first); 

輸出:

1) 730600.00 ns 

2) 53000.00 ns 

-0.6776 

這意味着字符串函數(也用foreach)比正則表達式函數更快;)

+0

我認爲你還沒有在性能優化方面做過工作,split方法和foreach循環itslef對性能至關重要,因此我總是儘量避免它們,這就是爲什麼我要求在我的正則表達式中題。 – 2010-10-21 12:39:29

+0

請檢查我的答案的'編輯'部分。 – 2010-10-21 13:53:59

+0

嗯,很好的例子,我印象深刻,我曾經使用Split方法和foreach循環,他們都是性能的關鍵,所以我們用戶的替代品。 – 2010-10-24 10:14:01

相關問題