B.McKee
B.McKee

Reputation: 430

C# Why isn't my RegEx matching? This one is really simple

I've tried several versions of how many "\" to get the ()'s to match. The pattern needs one, plus one to get it in the string.

--fixme.h--

#
_TARGET_VERSION = $(_TARGET_VERSION_GREEN)

#

--Program.cs--

static void Main(string[] args)
{
    var expr = "(_TARGET_VERSION = \\$\\(_TARGET_VERSION_GREEN\\))";
    var repl = "!if 0\n$1\n!endif";

    var content = File.ReadAllText("fixme.h");
    var searchOptions = RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline;
    var matched = Regex.Match(content, expr, searchOptions);
    if (matched.Success)
    {
        var newContent = Regex.Replace(content, expr, repl, searchOptions);
        File.WriteAllText("fixed.h", newContent);
    }
}

Upvotes: 1

Views: 55

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626851

The problem is with the searchOptions as the RegexOptions.IgnorePatternWhitespace makes the whitespace in the pattern formatting, all whitespace chars are removed from the pattern when compiling the regex object. The RegexOptions.Multiline is redundant here can could be removed.

Since you say you can't change the code much and can't remove searchOptions, you need to use the (?-x) inline modifier at the pattern start to deactivate the RegexOptions.IgnorePatternWhitespace option effect.

Here is the working code:

var expr = "(?-x)_TARGET_VERSION = \\$\\(_TARGET_VERSION_GREEN\\)";
var expr = @"(?-x)_TARGET_VERSION = \$\(_TARGET_VERSION_GREEN\)";

Or, you may escape all literal whitespace chars:

var expr = "_TARGET_VERSION\\ =\\ \\$\\(_TARGET_VERSION_GREEN\\)";
var expr = @"_TARGET_VERSION\ =\ \$\(_TARGET_VERSION_GREEN\)";

Note I removed the outer capturing parentheses from the regex pattern and the $1 with $& (a whole match backreference) in the replacement pattern.

See the C# demo online:

var expr = "(?-x)_TARGET_VERSION = \\$\\(_TARGET_VERSION_GREEN\\)";
var repl = "!if 0\n$&\n!endif";
var content = @"#
_TARGET_VERSION = $(_TARGET_VERSION_GREEN)

#";
var searchOptions = RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline;
var matched = Regex.Match(content, expr, searchOptions);
if (matched.Success)
{
    var newContent = Regex.Replace(content, expr, repl, searchOptions);
    Console.WriteLine(newContent);
}

Output:


#
!if 0
_TARGET_VERSION = $(_TARGET_VERSION_GREEN)
!endif

#

Upvotes: 1

Related Questions