Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitution number confusing

Tags:

c#

regex

Here's the code:

string myVar = "00000";
string myPtrn = "(.).(...)";
string mySub = "$1" + "1" + "$2";
string myResult = Regex.Replace(myVar, myPtrn, mySub);
MessageBox.Show("Before :\t" + myVar + "\nAfter :\t" + myResult);

The result is $11000.

I'd like to have 01000 from 00000.

But, I guess, $1 is confused with $11.

like image 812
Jason Avatar asked Jul 31 '16 03:07

Jason


1 Answers

You can put capturing group number inside {} to avoid any confusion for regex engine like

string mySub = "${1}" + "1" + "$2";

Ideone Demo

As suggested in comments, you can also use

string mySub = "${1}1$2";
like image 125
rock321987 Avatar answered Nov 01 '22 01:11

rock321987