How does MatchEvaluator works? ( C# regex replace)

Posted by Marin Doric on Stack Overflow See other posts from Stack Overflow or by Marin Doric
Published on 2010-04-06T20:01:35Z Indexed on 2010/04/06 20:03 UTC
Read the original article Hit count: 455

Filed under:
|
|
|
|

This is the input string 23x * y34x2. I want to insert " * " (star surrounded by whitespaces) after every number followed by letter, and after every letter followed by number. So my input string would look like this: 23 * x * y * 34 * x * 2. This is the regex that does the job: @"\d(?=[a-z])|a-z". This is the function that I wrote that inserts the " * ".

        Regex reg = new Regex(@"\d(?=[a-z])|[a-z](?=\d)");   
    MatchCollection matchC;
    matchC = reg.Matches(input);
    int ii = 1;
    foreach (Match element in matchC)//foreach match I will find the index of that match
    {
        input = input.Insert(element.Index + ii, " * ");//since I' am inserting " * " ( 3 characters )
        ii += 3;                                        //I must increment index by 3
    }
    return input; //return modified input

My question how to do same job using .net MatchEvaluator? I'am new to regex and don't understand good replacing with MatchEvaluator. This is the code that I tried to wrote:

        Regex reg = new Regex(@"\d(?=[a-z])|[a-z](?=\d)");
    MatchEvaluator matchEval = new MatchEvaluator(ReplaceStar);
    input = reg.Replace(input, matchEval);
    return input;
}
public string ReplaceStar( Match match )
{
    //return What??
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about regex