2010-06-15 61 views
2

我的圖案串圖案如下:C#:循環通過在字符串

{(代碼)}
其中代碼是一個數字(最多6個數字),或2個字母,接着是多個。
例如:

{(45367)}
{(265367)}
{(EF127012)}

我想找到一個長字符串的所有事件,我不能只使用純正則表達式,因爲當我找到匹配時(例如記錄位置和匹配類型),我需要執行一些操作。

+0

的regex庫會記得在MatchCollection每個匹配的位置。你的意思是什麼類型?所有數字與字母?然後循環匹配並檢查字母... – 2010-06-15 16:43:58

回答

5

你指的是這樣做仍然可以使用正則表達式做什麼。請嘗試以下...

Regex regex = new Regex(@"\{\(([A-Z]{2}\d{1,6}|\d{1,6})\)\}"); 
String test = @"my pattern is the following: 

我想找到所有出現在一個很長的字符串

var matches = regex.Matches(test); 
foreach (Match match in matches) 
{ 
    MessageBox.Show(String.Format("\"{0}\" found at position {1}.", match.Value, match.Index)); 
} 

我希望幫助。

1
\{\(([A-Z]{2})?\d{1,6}\)\} 
 
\{   # a literal { character 
\(   # a literal (character 
(   # group 1 
    [A-Z]{2} # letters A-Z, exactly two times 
)?   # end group 1, make optional 
\d{1,6}  # digits 0-9, at least one, up to six 
\)   # a literal) character 
\}   # a literal } character 
+0

我應該如何處理這個正則表達式?我如何使用它來獲得每場比賽的位置? – ilann 2010-06-15 16:43:02

+1

在C#中,在這個網站和其他地方有幾千個*如何使用正則表達式的例子。找到它們不是那麼難。 – Tomalak 2010-06-15 16:45:45

0

未編譯的和未經測試的代碼樣品

public void LogMatches(string inputText) 
{ 
    var @TomalaksPattern = @"\{\(([A-Z]{2})?\d{6}\)\}"; // trusting @Tomalak on this, didn't verify 
    MatchCollection matches = Regex.Matches(inputText, @TomalaksPattern); 
    foreach(Match m in matches) 
    { 
     if(Regex.Match(m.Value, @"\D").Success) 
      Log("Letter type match {0} at index {1}", m.Value, m.Index); 
     else 
      Log("No letters match {0} at index {1}", m.Value, m.Index); 
    } 
} 
0
foreach (Match m in Regex.Matches(yourString, @"(?:[A-Za-z]{2})?\d{1,6}")) 
{ 
    Console.WriteLine("Index=" + m.Index + ", Value=" + m.Value); 
}