C#Regex在调试字符串中查找所有字符串expect

时间:2012-06-14 02:53:04

标签: c# regex regex-negation

首先,我只能使用C#正则表达式,因此建议其他语言或非正则表达式解决方案不会有帮助。现在问。

我必须在代码中找到所有字符串(几千个文件)。基本上有6种情况:

   string a = "something"; // output" "something"
   sring b = "something else" + " more"; // output: "something else" and " more"
   Print("this should match"); // output: "this should match"
   Print("So" + "should this"); // output: "So" and "should this"
   Debug("just some bebug text"); // output: this should not match
   Debug("more " + "debug text"); // output: this should not match

正则表达式应该匹配前4(我只需要引号内的什么,而Print也可以是任何其他功能)

到目前为止,我有这个,它返回引号中的任何内容:

 ".*?"

1 个答案:

答案 0 :(得分:1)

简而言之: @"^(?!Debug\("")([^""]*""(?<Text>[^""]*)"")*.*$"

它的作用:

  • 如果字符串以Debug("
  • 开头,则不匹配
  • 沿着字符串运行,直到遇到第一个",然后经过它
    • 如果找不到"并且它到达字符串的末尾,则会停止。
  • 将“录制”开始到名为Text
  • 的群组中
  • 沿着字符串运行,直到它遇到下一个",停止录制,然后经过它。
  • 返回第2步

结果:您在名为"的群组中Text之间包含所有字符串。

您还可以做什么:在调试之前将其转换为多行正则表达式并支持whitepsaces(\s)作为更好的过滤器。

进一步使用示例和测试:

var regex = new Regex(@"^(?!Debug\("")([^""]*""(?<Text>[^""]*)"")*.*$");

var inputs = new[]
                 {
                     @"string a = ""something"";",
                     @"sring b = ""something else"" + "" more"";",
                     @"Print(""this should match"");",
                     @"Print(""So"" + ""should this"");",
                     @"Debug(""just some bebug text"");",
                     @"Debug(""more "" + ""debug text"");"
                 };

foreach (var input in inputs)
{
    Console.WriteLine(input);
    Console.WriteLine("=====");

    var match = regex.Match(input);

    var captures = match.Groups["Text"].Captures;

    for (var i = 0; i < captures.Count; i++)
    {
        Console.WriteLine(captures[i].Value);
    }

    Console.WriteLine("=====");
    Console.WriteLine();
}

<强>输出:

string a = "something";
=====
something
=====

sring b = "something else" + " more";
=====
something else
 more
=====

Print("this should match");
=====
this should match
=====

Print("So" + "should this");
=====
So
should this
=====

Debug("just some bebug text");
=====
=====

Debug("more " + "debug text");
=====
=====