【问题标题】:RegEx Match is not working正则表达式匹配不起作用
【发布时间】:2014-04-08 13:03:40
【问题描述】:

如果结果不成功,编译器只是停止,调试也只是停止,但没有错误,它只是停止。 如果 Result 是成功的,它可以工作,但 else 部分不工作,但是如果 Result 不成功,编译器只是停止,我该怎么办?

Match Result = Regex.Match(file, pattern);

if(Result.Success)
{
    // This part works
}
else
{
    // this is not working
}

这里有一个try catch,只是提一下。

【问题讨论】:

  • 向我们展示一个测试字符串和你的模式
  • “如果结果不成功,编译器只是停止,我会这样做”:不执行停止,编译器不会停止。编译是将代码转换为机器可执行的程序的操作。当您测试正则表达式是否通过时,您处于执行部分,而不是编译部分。

标签: c# regex visual-studio-2012 match


【解决方案1】:

else 块仅在 if 块失败时执行。在您的情况下,正则表达式已成功匹配,因此您的 else{ } 不会被执行。

如果不匹配,请不要担心。如果正则表达式不匹配,它将返回 false 并且您的 else{ } 将被执行。

【讨论】:

  • @BlueTrin,你的意思其实是很糟糕吧?
  • 不,你明白他在他的问题中的意思并解决了这个问题,我投了赞成票。
  • 这不是问题所在。如果正则表达式失败,则编译器将停止并且调试也将停止。看起来 Match 没有返回任何东西或类似的东西。
【解决方案2】:

我认为问题不在于成功是真是假。我试过这段代码,它可以工作:

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

namespace RegexTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1, s2, s0;
            //Regex regex;
            Match match;
            s0 = "l'insostenibile leggerezza dell'essere";
            s1 = "g.+z";
            s2 = "'.*'";
            try
            {
                match = Regex.Match(s0, s1);
                if(match.Success)
                {
                }
                else
                {
                }
                match = Regex.Match(s0, s2);
                if(match.Success)
                {
                }
                else
                {
                }
                s1 = "x.+r";
                match = Regex.Match(s0, s1);
                if(match.Success)
                {
                }
                else
                {
                }
            }
            catch(Exception ex)
            {
            }

        }
    }
}

你检查过条款吗?在我的代码中替换您的子句,然后重试。

【讨论】:

    猜你喜欢
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多