我有以下字符串:
abc
def
abc
xyz
pop
mmm
091
abc
我需要将所有出现的abc
替换为数组["123", "456", "789"]
中的那些,因此最终的字符串将如下所示:
123
def
456
xyz
pop
mmm
091
789
我想在没有迭代的情况下完成它,只需要单个表达式。我该怎么办?
答案 0 :(得分:5)
这是“单表达式版本”:
编辑代表Lambda for 3.5
string[] replaces = {"123","456","789"};
Regex regEx = new Regex("abc");
int index = 0;
string result = regEx.Replace(input, delegate(Match match) { return replaces[index++];} );
测试here
答案 1 :(得分:3)
在没有迭代的情况下完成,仅使用单个表达式
此示例使用静态Regex.Replace Method (String, String, MatchEvaluator),它使用MatchEvaluator Delegate (System.Text.RegularExpressions)替换队列中的匹配值并返回字符串作为结果:
var data =
@"abc
def
abc
xyz
pop
mmm
091
abc";
var replacements = new Queue<string>(new[] {"123", "456", "789"});
string result = Regex.Replace(data, "(abc)", replacements.Dequeue());
<强>结果强>
123
def
456
xyz
pop
mmm
091
789
.Net 3.5代表
而我只限于3.5。
Regex.Replace(data, "(abc)", delegate(Match match) { return replacements.Dequeue(); } )