0

首先,我只能使用 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 个(我只需要引号内的内容,打印也可以是任何其他函数)

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

 ".*?"
4

1 回答 1

1

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

它能做什么:

  • 不匹配以开头的字符串Debug("
  • 沿着绳子跑,直到遇到第一个",然后越过它
    • 如果"没有找到 a 并且它到达了字符串的末尾,它将停止。
  • 开始“录制”到一个名为Text
  • 沿着字符串运行,直到遇到下一个",停止录制,然后越过它。
  • 返回步骤 2

结果:"您在一个名为 的组中拥有 ' 之间的所有字符串Text

剩下要做的事情:将其转换为多行正则表达式并在 Debug 之前支持 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");
=====
=====
于 2012-06-14T03:37:42.397 回答