正则表达式匹配不起作用

时间:2010-03-23 20:59:23

标签: .net regex

我正在尝试将以下字符串分为三组。

0:0:Awesome:awesome

那是“ 0 ”,“ 0 ”和“太棒了:太棒了

使用此正则表达式:

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

它适用于在线正则表达式服务:http://rubular.com/r/QePxt57EwU

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

3 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:1)

如果您想访问匹配的群组,以下内容可以帮助您

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

答案 2 :(得分:0)

我认为这个正则表达式适合

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

然后你可以得到'num'和'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:真棒:太棒了'

相关问题