How to get the found substring when using the Regex.Replace method?

I use this code to replace all found values ​​in a string by index:

int i = 0;
input = "FGS1=(B+A*10)+A*10+(C*10.5)";
Regex r = new Regex("([A-Z][A-Z\\d]*)");
bool f = false;
MatchEvaluator me = delegate(Match m)
{
  f = true;
  i++;
  return "i" + i.ToString();
};
do { f = false; input = r.Replace(input, me); } while (f);
//expected result: input == "i1=(i2+i3*10)+i4*10+(i5*10.5)"

But I have to make it harder because I need to do something with the found value. For instance:

MatchEvaluator me = delegate(Match m)
{
  foundValue = /*getting value*/;
  if (foundValue = "A") i--;
  f = true;
  i++;
  return "i" + i.ToString();
};

Expected result for this code: "i1=(i2+i2*10)+i2*10+(i3*10.5)"

+4
source share
3 answers

Assuming you need to implement a variable assignment in which you assign ix (where x is the number increasing) for each variable, and then reuse this value if it appears, we can write the following code to solve your problem:

var identifiers = new Dictionary<string, string>();
int i = 0;
var input = "FGS1=(B+A*10)+A*10+(C*10.5)";
Regex r = new Regex("([A-Z][A-Z\\d]*)");
bool f = false;

MatchEvaluator me = delegate(Match m)
{
    var variableName = m.ToString();

    if(identifiers.ContainsKey(variableName)){
        return identifiers[variableName];
    }
    else {
        i++;
        var newVariableName = "i" + i.ToString();
        identifiers[variableName] = newVariableName;
        return newVariableName;
    }
};

input = r.Replace(input, me);
Console.WriteLine(input);

This code should print: i1 = (i2 + i3 * 10) + i3 * 10 + (i4 * 10.5)

+2
source

Groups match, . - , 1:

string foundValue = m.Groups[1].Value;
if (foundValue == "A") i--;
+5

Guffa should answer your question, I just want to share my alternative way to solve your problem, using more features from .NET Regex (if I understand your problem correctly):

int i = 1;
string input = "FGS1=(B+A*10)+A*10+(C*10.5)";   
var lookUp = new Dictionary<string, string>();
var output = Regex.Replace(input, 
             "([A-Z][A-Z\\d]*)", 
             m => { 
                if(!lookUp.ContainsKey(m.Value))
                {           
                    lookUp[m.Value] = "i" + i++;            
                }
                return lookUp[m.Value]; 
            });
Console.WriteLine(output);      //i1=(i2+i3*10)+i3*10+(i4*10.5)

I use a dictionary to track duplicate matches

This should work even if your repetition is different from "A". In your original solution, it is checked specifically for "A", which is rather fragile.

+1
source

Source: https://habr.com/ru/post/1569196/


All Articles