Home > Blockchain >  C# Regular Expression how to update one capture while preserving all the other parts of the input?
C# Regular Expression how to update one capture while preserving all the other parts of the input?

Time:10-31

imagine we have the following input:

xxxxx-yyy-zzz

and we just need to capture yyy and update this capture while keeping all the rest for example:

xxxxx-yyyupdated-zzz

what is the best way to do it? I tried Replace but it doesn't keep the input not matching the capture...

So I did resolve in 3 steps:

  • Check if capture match
  • Replace the capture match with updated value
  • Replace the capture in the input string with the new updated capture

Is there a way to do all this in one step? RegExp.Replace doesn't work this way...

Thanks

CodePudding user response:

I tried Replace but it doesn't keep the input not matching the capture...

I think that is an incorrect observation.

var input = "aaaaaaa-lllll-xxxxx-yyy-zzz-cccccc";

var result = Regex.Replace(input, "(yyy)", "$1updated");

Console.WriteLine(result);  // "aaaaaaa-lllll-xxxxx-yyyupdated-zzz-cccccc"

CodePudding user response:

You can use the following Regex

Regex.Replace(yourString, "(. ?xxxxx-yyy)(. )", "$1updated$2")

This uses two capture groups, and replaces them with the first capture group, followed by the text updated followed by the second group.

  • Related