(?<=#if DEBUG(?:(?!#endif\b).)*)Logging\.Log[^\r\n]*(?=.*#endif)
будет соответствовать Logging.Log
и всем остальным, что следует в этой строке, только если оно находится между #if DEBUG
и #endif
.Обратите внимание, что вам нужно использовать RegexOptions.Singleline
, чтобы это работало.Это регулярное выражение опирается на функцию, которой обладают лишь немногие движки регулярных выражений, а именно бесконечное повторение внутри взгляда позади утверждений .К счастью, среди них есть .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)
.