Regex.Replace 中的 MatchEvaluator 如何工作? [英] How does MatchEvaluator in Regex.Replace work?

查看:16
本文介绍了Regex.Replace 中的 MatchEvaluator 如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是输入字符串23x * y34x2.我想在每个数字后跟字母和每个字母后跟数字后插入 " * " (由空格包围的星号).所以我的输出字符串看起来像这样:23 * x * y * 34 * x * 2.

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.

这是完成这项工作的正则表达式:@"d(?=[a-z])|[a-z](?=d)".这是我写的插入" * "的函数.

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

我的问题是如何使用 .net MatchEvaluator 做同样的工作?我是 regex 的新手,不明白用 MatchEvaluator 替换的好方法.这是我尝试编写的代码:

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??
}

推荐答案

A MatchEvaluator 是一个委托,它接受一个 Match 对象并返回一个应该被替换而不是匹配的字符串.您还可以参考比赛中的组.您可以按如下方式重写代码:

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 + " * ";
});

举例说明这是如何工作的,第一次调用委托时,Match 参数将匹配字符串 "3".在这种情况下,委托被定义为将匹配本身作为与 " * " 连接的字符串返回.所以第一个"3"被替换为"3 * ".

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.

这篇关于Regex.Replace 中的 MatchEvaluator 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆