【问题标题】:How does MatchEvaluator in Regex.Replace work?Regex.Replace 中的 MatchEvaluator 如何工作?
【发布时间】:2011-02-04 23:35:24
【问题描述】:

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

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

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 做同样的工作?我是正则表达式的新手,不理解用MatchEvaluator 替换的好方法。这是我尝试编写的代码:

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

【问题讨论】:

    标签: c# .net regex replace matchevaluator


    【解决方案1】:

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

    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 * "

    过程以这种方式继续,原始字符串中的每个匹配都调用一次委托。

    【讨论】:

    • 我想提一下,由于添加了 lambda 表达式 delegate(Match m) { return m.Value + " * "; } 可以替换为 (Match m) => return m.Value + " * ";。耶进步。
    • ^ 可以进一步简化为 (m) => m.Value + "*"
    • ^可以通过省略括号和使用字符串插值来简化:-) m => $"{m.Value}*"
    猜你喜欢
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多