如何在单程中替换多次出现?
How to replace multiple occurrences in single pass?
我有以下字符串:
abc
def
abc
xyz
pop
mmm
091
abc
我需要将所有出现的 abc
替换为数组 ["123", "456", "789"]
中的那些,这样最终的字符串将如下所示:
123
def
456
xyz
pop
mmm
091
789
我想不用迭代,只用一个表达式。我该怎么做?
这是一个"single expression version":
编辑: Delegate 而不是 3.5 的 Lambda
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
do it without iteration, with just single expression
此示例使用静态 Regex.Replace Method (String, String, MatchEvaluator) which uses a MatchEvaluator Delegate (System.Text.RegularExpressions) 将替换队列中的匹配值和 returns 作为结果的字符串:
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)", // Each match will be replaced with a new
(mt) => // queue item; instead of a one string.
{
return replacements.Dequeue();
});
结果
123
def
456
xyz
pop
mmm
091
789
.Net 3.5 代表
whereas I am limited to 3.5.
Regex.Replace(data, "(abc)", delegate(Match match) { return replacements.Dequeue(); } )
我有以下字符串:
abc
def
abc
xyz
pop
mmm
091
abc
我需要将所有出现的 abc
替换为数组 ["123", "456", "789"]
中的那些,这样最终的字符串将如下所示:
123
def
456
xyz
pop
mmm
091
789
我想不用迭代,只用一个表达式。我该怎么做?
这是一个"single expression version":
编辑: Delegate 而不是 3.5 的 Lambda
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
do it without iteration, with just single expression
此示例使用静态 Regex.Replace Method (String, String, MatchEvaluator) which uses a MatchEvaluator Delegate (System.Text.RegularExpressions) 将替换队列中的匹配值和 returns 作为结果的字符串:
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)", // Each match will be replaced with a new
(mt) => // queue item; instead of a one string.
{
return replacements.Dequeue();
});
结果
123
def
456
xyz
pop
mmm
091
789
.Net 3.5 代表
whereas I am limited to 3.5.
Regex.Replace(data, "(abc)", delegate(Match match) { return replacements.Dequeue(); } )