namezero
namezero

Reputation: 2293

Regex match an optional ending and prefer to do so

I' failry new to regex, and wish to match these two lines:

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

So far I have this:

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

However, the last part is giving me trouble:

\r\n"

I can match this and make it optional, no problem, with this:

(\\r\\n")

However, I wish to capture it in a group if it is there (I think greedy is what I need) So far, all my attempts have resulted in it not being matched if it is there because it is optional.

Can I force the regex engine to continue searching even if it is there, so I can get a capture group for it?

Upvotes: 0

Views: 260

Answers (1)

Eugene Ryabtsev
Eugene Ryabtsev

Reputation: 2301

You want something like this:

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));

Which gives an output like this:

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

The regex is a bit ugly, but that's because I allow for more spaces. Generally it consists of:

(?<=...) #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

Upvotes: 1

Related Questions