Bizarre Replace Behavior

mskeel

Senior Contributor
Joined
Oct 30, 2003
Messages
913
The following command gives me an unexpected output and I would like to understand what is happening so I can fix it.

Code:
Dim line as string = "replace $$this$$ with something similiar."
Dim expression as string = "\$\$this\$\$"
Dim replacement as string = "$$similiar$$"

Dim val as string = Regex.Replace(line, expression, replacement)

I think val should be "replace $$similiar$$ with something similiar." But when I run a test the answer is really "replace $similiar$ with something similiar." Where did the additional dollar signs go?

If you replace replacement with "$$$similiar$$$", val will get "replace $$similiar$$ with something similiar."

And if you change replacement to "$similiar$" then all works as I think it should, "replace $similiar$ wtih something similiar."

What is going on here? I know that $ is a regex character so I escaped it with the \, but what explains the odd behavior?
 
I figured out what the issue is.

As it turns out, the replace string in Regex.Replace has special properties and characters, one of which is the $. The replacement string will interpret a subset of regular expression syntax, substitutions, which is designated by the $.

The MSDN tells all about how to use $.

The basic problem I was having was with $$ escaping the $ character. So if I were to put a sinlge $ in, $similiar$, the replacement would simply put the $ character in becuase there is no syntax defined for it. If I do $$, the replacement string would escape the $ and only put a single $ in the replaced string. Likewise, $$$ => one escape and an additional $, so $$ in the end while $$$$ => $$ and so on.

Absolutely bizarre behavior. A little anoying if you don't know it's there, but I see it's purpose now that I do. Two different ways to escape $...not the best thing in the world if you ask me.
 
Back
Top