Home > Net >  Find each instance and replace with unique value in string
Find each instance and replace with unique value in string

Time:02-10

I have some text in a string as below:

{121:SOMETHING1}}{4:
.
.
.
{121:SOMETHING2}}{4:
.
.
.
{121:SOMETHING3}}{4:

I want to sequentially find and replace the value between 121: and the first }. I can successfully do this using the following code in C#

       var rx = @"121:(?<value>[\s\S] ?)}";           
       string temp = tag121;

       string stringToChange = //as above
       for (var m = Regex.Match(stringToChange , rx); m.Success; m = m.NextMatch())
       {
           temp = generateUniqueValue()

           stringToChange= Regex.Replace(stringToChange, m.Value, temp);

        }

However, if instead of having different values between 121: and } I have exactly the same value for all the tags e.g instead of SOMETHING1, SOMETHING 2 etc, I just have SOMETHING for all the lines, then this code does not work. It ends up setting just one value for all the lines instead of unique values for each.

CodePudding user response:

When all the lines in the string are all {121:SOMETHING}}{4:, the first cycle of the loop already replaced every SOMETHING in the string to first call result of generateUniqueValue(). You can see that happening by printing out stringToChange in the end of every for-loop cycle. (A good way to debug when working around regex, too)

You need to consider a new approach or look at what you trying to achieve again:

  • Is it acceptable that there are at least 2 lines with same value in the input?
  • Should lines with same values be replaced into different UniqueValue?

If answers to both questions are yes, one approach I suggest is replace line by line. Not optimal I guess though...

  1. Split the string by lines. String.Split("\\n") Maybe?
  2. Foreach through that split string array.
  3. Find part to replace by regex {121:([^}] )} - Group 1 of the match is the string you need to replace.
  4. After foreach loop, concat the array into one single string again.

Reference:

  • Related