2010-03-23 93 views
0

我试图将以下字符串分组为三个组。正则表达式匹配不能正常工作

0:0:Awesome:awesome 

这是 “”, “” 和 “真棒:真棒

使用正则表达式:

^([0-9]+)\:([0-9]*)\:(.*)$ 

它可以在网上正则表达式罚款服务:http://rubular.com/r/QePxt57EwU

但似乎.NET不同意。 Picture of Regex problem from Visual Studio http://xs.to/image-3F8A_4BA916BD.jpg

+1

Rubular使用Ruby的regexp引擎,它与.NET的不一样。对于这种模式,我没有看到它不应该起作用的任何理由,但只是要记住。 – 2010-03-23 21:01:44

+0

添加到丹尼尔说,一个伟大的测试.NET正则表达式的工具是Expresso,虽然测试你的工作似乎对我很好。 http://www.ultrapico.com/Expresso.htm – FrustratedWithFormsDesigner 2010-03-23 21:03:34

回答

5

MatchCollection包含迭代地将正则表达式应用于源字符串的结果。在你的情况下,只有1个匹配 - 所以结果是正确的。你可以在比赛中获得多次获胜。这是你想比较的 - 而不是比赛的数量。

MatchCollection matches = RegEx.Matches("0:0:Awesome:awesome", 
             "^([0-9]+)\:([0-9]*)\:(.*)$"); 

if(matches.Count != 1 && matches[0].Captures.Count != 3) 
    //... 
+0

我非常感谢你!愚蠢的错误。 – 2010-03-23 21:18:37

0

我觉得这个正则表达式会适合

 
(?<nums>\d+\:?)+(?<rest>.*) 

然后你就可以得到“民”和“休息”的分组在一起,如图

 
public Regex MyRegex = new Regex(
     "^(?<nums>\\d+\\:?)+(?<rest>.*)$", 
    RegexOptions.IgnoreCase 
    | RegexOptions.CultureInvariant 
    | RegexOptions.IgnorePatternWhitespace 
    | RegexOptions.Compiled 
    ); 
MatchCollection ms = MyRegex.Matches(InputText); 

InputText将包含样品'0:0:Awesome:Awesome'

1

当你想访问匹配的组ing可以帮助你

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 

namespace Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var pattern = "^([0-9]+)\\:([0-9]*)\\:(.*)$"; 

      var matches = Regex.Match("0:0:Awesome:awesome", pattern); 

      foreach (var match in matches.Groups) 
       Console.WriteLine(match); 
     } 
    } 
}