代码之家  ›  专栏  ›  技术社区  ›  はると

regex匹配不起作用

  •  0
  • はると  · 技术社区  · 15 年前

    我想把下面的字符串分成三组。

    0:0:Awesome:awesome
    

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

    使用此正则表达式:

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

    它在在线Regex服务上运行良好: http://rubular.com/r/QePxt57EwU

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

    3 回复  |  直到 15 年前
        1
  •  5
  •   LBushkin    15 年前

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

    MatchCollection matches = RegEx.Matches("0:0:Awesome:awesome",
                                            "^([0-9]+)\:([0-9]*)\:(.*)$");
    
    if( matches.Count != 1 && matches[0].Captures.Count != 3 )
      //...
    
        2
  •  1
  •   PetPaulsen    15 年前

    当您想访问匹配的组时,以下内容可以帮助您

    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);
            }
        }
    }
    
        3
  •  0
  •   t0mm13b    15 年前

    我想这个雷格夫适合

    (?<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:太棒了:太棒了”