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

查看:194
本文介绍了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(?= [az])| [az](?= \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天全站免登陆