Home > Blockchain >  replace captured item in regular expression replace in C#
replace captured item in regular expression replace in C#

Time:01-09

I have write some code as below

Regex hex2ToHex4 = new("/\\[x][0-9a-f]{4}/gi");
hex2ToHex4.Replace(input, ???);

The problem is: how can i replace the match item \x???? to \u????

CodePudding user response:

This uses ( and ) in the regular expression to create a capture group. And in the replacement uses $1 to output that capture group in the replacement text.

Regex hex2ToHex4 = new Regex(@"\\[x]([0-9a-f]{4})");
resultString = hex2ToHex4.Replace(input, @"\u$1");

Note this can also be more simply written as:

resultString = Regex.Replace(input, @"\\x([0-9a-f]{4})", @"\u$1");

Note the [ and ] not required around the x.

  •  Tags:  
  • Related