【发布时间】: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