正则表达式匹配可选的结尾,并且喜欢这样做

时间:2012-09-06 09:24:37

标签: c# regex

我对新的正则表达式失败了,并且希望匹配这两行:

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
    "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n"

到目前为止,我有这个:

(\\s+)?(\")?(#)(if\\s+!defined\\(AFX_RESOURCE_DLL\\)\\s+\\|\\|\\s+defined\\()(\\w+)(\\))

然而,最后一部分给我带来了麻烦:

\r\n"

我可以匹配这个并使其可选,没问题,用这个:

(\\r\\n")

但是,如果它存在的话,我希望将它捕获到一个组中(我认为贪婪是我需要的) 到目前为止,我所有的尝试都导致它不匹配,因为它是可选的。

我可以强制正则表达式引擎继续搜索,即使它在那里,所以我可以为它获得一个捕获组吗?

1 个答案:

答案 0 :(得分:1)

你想要这样的东西:

string pattern = @"(?<=#if\s+!\s*defined\s*\(\s*AFX_RESOURCE_DLL\s*\)\s*\|\|\s*defined\s*\(\s*)\w+(?=\s*\))";
string result = Regex.Replace(s, pattern, match => Hash(match.Value));

这给出了这样的输出:

#if !defined(AFX_RESOURCE_DLL) || defined(QUZYX1RBUkdfRU5V)
   "#if !defined(AFX_RESOURCE_DLL) || defined(QUZYX1RBUkdfRU5V)\r\n"

正则表达式有点难看,但这是因为我允许更多空格。通常它包括:

(?<=...) #A positive lookbehind with text that must appear before the match
\w+      #Text to replace
(?=...)  #A positive lookahead with text that must appear after the match