Mithil
Mithil

Reputation: 3770

Regex.Replace not working

I am having a strange issue with Regex.Replace

string test = "if the other party is in material breach of such contract and, after <span style=\"background-color:#ffff00;\">forty-five (45)</span> calendar days notice of such breach";
string final = Regex.Replace(test, "forty-five (45)", "forty-five (46)", RegexOptions.IgnoreCase);

the "final" string still shows "forty-five (45)". Any idea why? I am assuming it has to do something with the tag. How do I fix this?

Thanks

Upvotes: 1

Views: 11347

Answers (3)

Nicholas Carey
Nicholas Carey

Reputation: 74227

Parentheses are special in regular expressions. They delimit a group, to allow for things such as alternation. For example, the regular expression foo(bar|bat)baz matches:

  • foo, followed by
  • either bar OR bat, followed by
  • baz

So, a regular expression like foo(bar) will never match the literal string foo(bar). What it will match is the literal string foobar. Consequently, you need to escape the metacharacters. In C#, this should do you:

string final = Regex.Replace(test, @"forty-five \(45\)", "forty-five (46)", RegexOptions.IgnoreCase);

The @-quoted string helps avoid headaches from excessive backslashes. Without it, you'd have to write "forty-five \(45\)".

Upvotes: 1

Vasili Syrakis
Vasili Syrakis

Reputation: 9591

If you are unable to escape the parenthesis, put them in a character class:

forty-five [(]45[)]

Upvotes: 0

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

Escape the parenthesis. Depending on the language, might require two back slashes.

string final = Regex.Replace(test, "forty-five \(45\)", "forty-five (46)", RegexOptions.IgnoreCase);

Basically, parenthesis are defined to mean something, and by escaping the characters, you are telling regex to use the parenthesis character, and not the meaning.

Better yet, why are you using a Regex to do this at all? Try just doing a normal string replacement.

string final = test.Replace("forty-five (45)", "forty-six (46)")

Upvotes: 6

Related Questions