【问题标题】:Regular expression works in tester but not in my code [duplicate]正则表达式在测试器中有效,但在我的代码中无效[重复]
【发布时间】:2014-07-25 22:43:56
【问题描述】:

这是我的代码。

        static void Main(string[] args)
        {
            string pattern = 
@"^(?<p1>.*?)(?<c0>\w+)(?<s1>.*?)$
^(?<p2>.*?)\k<c0>(?<s2>.*?)$
^\k<p1>(?<c1>\w+)\k<s1>$
^\k<p2>\k<c1>\k<s2>$";

            string text = 
@"            if (forwardRadioButton.IsChecked.Value)
                car = car.Forward(distance);
            else if (backwardRadioButton.IsChecked.Value)
                car = car.Backward(distance);
            else if (forwardLeftRadioButton.IsChecked.Value)
                car = car.ForwardLeft(distance);";

            var mc = Regex.Matches(text, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);

            Console.WriteLine(mc.Count);
            Console.ReadKey();
        }

它找不到匹配项。

但如果我在 .NET 测试器中测试正则表达式和文本,它可以找到匹配项。

我是否遗漏了代码中的任何内容?如何使模式起作用?

【问题讨论】:

  • 对 Regex 知之甚少,但我记得 SingleLine 和 MultiLine 选项非常不直观,并且在我曾经使用的至少一个测试程序中实现不一致。跨度>
  • 我使用了来自 Ultrapico 的名为 Expresso 的测试程序并取得了一些成功。也有在线 Regex 测试页面,但通常不兼容 .Net。

标签: c# .net regex


【解决方案1】:

问题在于你的行尾。

您在代码中创建的内联字符串以\r\n 结尾,而正则表达式引擎需要\n 才能匹配$

只需在匹配之前插入这些行,它就会起作用:

 pattern = pattern.Replace("\r\n", "\n");
 text = text.Replace("\r\n", "\n");

这去掉了\r,一切都应该很好。

【讨论】:

    【解决方案2】:

    尝试做这样的事情:

    string yourtext = "yourtext";
    Regex yourregex = new Regex(@"put your regex pattern here" , RegexOptions.IgnoreCase | RegexOptions.Multiline);
    
    //put Matches in Collection
    MatchCollection matchesCollection = yourregex.Matches(yourtext);
    
    //output
    Console.WriteLine(matchesCollection.Count);
    

    【讨论】:

    • 看起来您只是将静态方法更改为实例方法。问题依然存在。
    【解决方案3】:

    我可能会解决问题。我删除了模式中的 ^ 和 $,现在我有 1 个匹配项。

    如果模式本身有多行,你不应该把^和$放在中间行。

                string pattern =
    @"^(?<p1>.*?)(?<c0>\w+)(?<s1>.*?)
    (?<p2>.*?)\k<c0>(?<s2>.*?)
    \k<p1>(?<c1>\w+)\k<s1>
    \k<p2>\k<c1>\k<s2>$";
    
                string text = 
    @"            if (forwardRadioButton.IsChecked.Value)
                    car = car.Forward(distance);
                else if (backwardRadioButton.IsChecked.Value)
                    car = car.Backward(distance);
                else if (forwardLeftRadioButton.IsChecked.Value)
                    car = car.ForwardLeft(distance);";
    
                var mc = Regex.Matches(text, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
    
                Console.WriteLine(mc.Count);
                Console.ReadKey();
    

    【讨论】:

    • 这是一个错误的解决方案,因为当您删除^$ 时,您将不再匹配整行。如果您需要解决方案,则需要做其他事情。
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多