How does MatchEvaluator in Regex.Replace work?

前端 未结 1 1042
無奈伤痛
無奈伤痛 2020-12-05 12:48

This is the input string 23x * y34x2. I want to insert \" * \" (star surrounded by whitespaces) after every number followed by letter, and after ev

1条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 13:31

    A MatchEvaluator is a delegate that takes a Match object and returns a string that should be replaced instead of the match. You can also refer to groups from the match. You can rewrite your code as follows:

    string input = "23x * y34x2";
    Regex reg = new Regex(@"\d(?=[a-z])|[a-z](?=\d)");
    string result = reg.Replace(input, delegate(Match m) {
        return m.Value + " * ";
    });
    

    To give an example of how this works, the first time the delegate is called, Match parameter will be a match on the string "3". The delegate in this case is defined to return the match itself as a string concatenated with " * ". So the first "3" is replaced with "3 * ".

    The process continues in this way, with delegate being called once for each match in the original string.

    0 讨论(0)
提交回复
热议问题