C#:循环通过在字符串

问题描述:

我的图案串图案如下:C#:循环通过在字符串

{(代码)}
其中代码是一个数字(最多6个数字),或2个字母,接着是多个。
例如:

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

我想找到一个长字符串的所有事件,我不能只使用纯正则表达式,因为当我找到匹配时(例如记录位置和匹配类型),我需要执行一些操作。

+0

的regex库会记得在MatchCollection每个匹配的位置。你的意思是什么类型?所有数字与字母?然后循环匹配并检查字母... – 2010-06-15 16:43:58

你指的是这样做仍然可以使用正则表达式做什么。请尝试以下...

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

我希望帮助。

\{\(([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

采用MatchEvaluator参数的唯一'Regex'方法是各种'Replace'重载,所以如果OP最终想要执行某种替换,这个建议才真正适用。 – LukeH 2010-06-15 16:59:02

未编译的和未经测试的代码样品

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

foreach (Match m in Regex.Matches(yourString, @"(?:[A-Za-z]{2})?\d{1,6}")) 
{ 
    Console.WriteLine("Index=" + m.Index + ", Value=" + m.Value); 
}