Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

c# - How does MatchEvaluator in Regex.Replace work?

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 output string would look like this: 23 * x * y * 34 * x * 2.

This is the regex that does the job: @"d(?=[a-z])|[a-z](?=d)". 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??
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...