2011-11-02 58 views
0

我在C#中的長字符串的字符串,我需要找到子看起來像這樣的:查找與特定模式C#字符串

number.number:number 

例如字符串:

text text 
965.435:001 text text sample 
7854.66:006 text text 

我想查找並以某種方式將965.435:001和7854.66:006保存爲字符串。

+2

您所需要的正則表達式是'\ d + \ \ d +:\ d +'。 – Heinzi

+0

謝謝,你能提供一個代碼示例嗎? – Afra

回答

7
  • \d的意思是 「數字」
  • +意味着 「一個或多個」
  • \.意味着字面點(單獨.將意味着 「任何字符」)
  • \b手段 「單詞邊界」(開始或字母數字「單詞」的結尾)。

所以,你的正則表達式將是

\b\d+\.\d+:\d+\b 

在C#:

MatchCollection allMatchResults = null; 
Regex regexObj = new Regex(@"\b\d+\.\d+:\d+\b"); 
allMatchResults = regexObj.Matches(subjectString); 
if (allMatchResults.Count > 0) { 
    // Access individual matches using allMatchResults.Item[] 
} else { 
    // Match attempt failed 
} 
+0

哇,謝謝! – Afra

0

使用正則表達式和捕捉到的事情..

發揮與此代碼...它應該得到你想要的東西...

string text = "your text"; 
     string pat = @"(\d*\.\d*:\d*)"; 

     // Instantiate the regular expression object. 
     Regex r = new Regex(pat, RegexOptions.IgnoreCase); 

     // Match the regular expression pattern against a text string. 
     Match m = r.Match(text); 
     int matchCount = 0; 
     while (m.Success) 
     { 
     Console.WriteLine("Match"+ (++matchCount)); 
     for (int i = 1; i <= 2; i++) 
     { 
      Group g = m.Groups[i]; 
      Console.WriteLine("Group"+i+"='" + g + "'"); 
      CaptureCollection cc = g.Captures; 
      for (int j = 0; j < cc.Count; j++) 
      { 
       Capture c = cc[j]; 
       System.Console.WriteLine("Capture"+j+"='" + c + "', Position="+c.Index); 
      } 
     } 
     m = m.NextMatch(); 
     } 
1

在下面的示例演示如何使用正則表達式查找字符串中的某些格式

class TestRegularExpressionValidation 
{ 
    static void Main() 
    { 
     string[] numbers = 
     { 
      "123-456-7890", 
      "444-234-22450", 
      "690-203-6578", 
      "146-893-232", 
      "146-839-2322", 
      "4007-295-1111", 
      "407-295-1111", 
      "407-2-5555", 
     }; 

     string sPattern = "^\\d{3}-\\d{3}-\\d{4}$"; 

     foreach (string s in numbers) 
     { 
      System.Console.Write("{0,14}", s); 

      if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern)) 
      { 
       System.Console.WriteLine(" - valid"); 
      } 
      else 
      { 
       System.Console.WriteLine(" - invalid"); 
      } 
     } 
    } 
} 
0

事情是這樣的:

var match = Regex.Match("\d+\.\d+:\d+") 
while (match.Success){ 
    numbersList.Add(match.Groups[0]) 
    match = match.NextMatch() 
}