Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get found substring while using Regex.Replace method?

Tags:

c#

regex

I'm using this code to replace all found values in string by indexes:

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 do it in more complex way, for what i have to do something with found value. For example:

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)"

like image 347
InfernumDeus Avatar asked Feb 12 '23 06:02

InfernumDeus


2 Answers

You can use the Groups collection in the match object to get the matched groups. The first item is the entire match, so the value from the first group is at index 1:

string foundValue = m.Groups[1].Value;
if (foundValue == "A") i--;
like image 64
Guffa Avatar answered Feb 13 '23 20:02

Guffa


Guessing you need to implement a variable assignment in which you assign ix (where x is an incrementing number) to 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)

like image 45
avenet Avatar answered Feb 13 '23 21:02

avenet