0

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

n.st
  • 946
  • 12
  • 27
Mithil
  • 3,700
  • 12
  • 30
  • 41

3 Answers3

6

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)")
PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142
  • 1
    I actually simplified the code for posting. The "search" and "replace" variables are dynamic. So I can't really escape anything. – Mithil Feb 05 '14 at 00:31
  • 1
    Why can't you escape ( and )? Those can be string replaced before regex replaced. – Erik Philips Feb 05 '14 at 00:37
  • @ErikPhilips the actual string might contain other special characters as well. So it won't be feasible to check on each special character. – Mithil Feb 05 '14 at 00:49
  • If that's the case, you probably want to do a replacement that doesn't involve regex. See my edit. – PearsonArtPhoto Feb 05 '14 at 00:52
  • It seems you don't have a clear understanding (or you haven't communicated it) of what your source and replacement values are. [Escaping special characters isn't that hard, I don't see the issue](http://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions). – Erik Philips Feb 05 '14 at 17:54
1

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\)".

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
0

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

forty-five [(]45[)]

Vasili Syrakis
  • 9,321
  • 1
  • 39
  • 56