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:

The pattern:

And the replacment string:

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:

One thought on “Mixing numbers and replacement strings

Comments are closed.