0

我有一个包含大量 #if 调试块的应用程序,如下所示:

#if DEBUG
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine("oldXml: " + oldXml.OuterXml);
                            Logging.Log("XmlDiff: " + diff_sb.ToString());
                Console.ForegroundColor = ConsoleColor.Cyan;
                            Logging.Log("2XmlDiff: " + diff_sb.ToString());
                Console.WriteLine("newXml: " + newXml.OuterXml);
                Console.ForegroundColor = ConsoleColor.Green;
#endif

我正在使用 Resharper 的搜索模式匹配功能,如果调试块,我需要能够在其中找到字符串“Logging.Log”的所有实例

有人知道这个模式搜索的正则表达式应该是什么吗?

4

2 回答 2

0
(?<=#if DEBUG(?:(?!#endif\b).)*)Logging\.Log[^\r\n]*(?=.*#endif)

Logging.Log只有在#if DEBUGand之间时,才会匹配以及该行后面的任何其他内容#endif。请注意,您需要使用RegexOptions.Singleline它才能工作。此正则表达式依赖于只有少数正则表达式引擎具有的功能,即在lookbehind assertions中无限重复。幸运的是,.NET 就是其中之一。

在 C# 中:

StringCollection resultList = new StringCollection();
Regex regexObj = new Regex(@"(?<=#if DEBUG(?:(?!#endif\b).)*)Logging\.Log[^\r\n]*(?=.*#endif)", RegexOptions.Singleline);
Match matchResult = regexObj.Match(subjectString);
while (matchResult.Success) {
    resultList.Add(matchResult.Value);
    matchResult = matchResult.NextMatch();
} 

解释:

# from the current position, look behind in the string to check...
(?<=           # whether it is possible to match...
 #if DEBUG     # the literal text # if DEBUG
 (?:           # followed by...
  (?!#endif\b) # (as long as we can't match #endif along the way)
  .            # any character
 )*            # any number of times
)              # end of lookbehind assertion.
Logging\.Log   # Then match Logging.Log,
[^\r\n]*       # followed by any character(s) except newlines.
(?=            # as long as there is (further up ahead)...
 .*#endif      # any number of characters, followed by #endif
)              # end of lookahead

如果您确定每个都#if DEBUG以 结尾#endif,那么您可以删除(?=.*#endif).

于 2010-09-30T06:28:26.403 回答
0

可能更简单的方法之一是分两个步骤。首先,使用正则表达式收集 和 之间的所有文本#if DEBUG#endif。然后遍历每个块并找到字符串“Logging.Log”。

如果要保留精确位置,则必须在第一步中保存每个块的偏移量,并在第二步中添加偏移量。

于 2010-09-30T03:43:58.750 回答