Mixing numbers and replacement strings

This is yet another thing that I found took me too long to find on Google. I’m using the .NET regular expressions, and looking to replace values in a string with numbers, and I need to use the special $1 symbols to keep some of my capture groups around.

So, suppose I have the text:
something.2005.txt

The pattern:
(.*)2005(.*)

And the replacment string:
$12008$2

This produces the undesirable result $12008.txt. Why? Well, the $1 has to be escaped in some way. Whatever it is that scans for variables is obviously interpreting this as $12008 instead of $1; either that’s invalid or the group doesn’t exist so it just uses the text. Personally I think I should be getting “2008.txt” in this case, as a raw $ should take $$ to create, but I won’t complain.

The solution? Surround the number of the group index in brackets:
${1}2008$2

One thought on “Mixing numbers and replacement strings

Comments are closed.