【问题标题】:How to replace multiple occurrences in single pass?如何在单遍中替换多次出现?
【发布时间】:2015-08-14 13:44:51
【问题描述】:

我有以下字符串:

abc
def
abc
xyz
pop
mmm
091
abc

我需要将所有出现的abc 替换为数组["123", "456", "789"] 中的那些,这样最终的字符串将如下所示:

123
def
456
xyz
pop
mmm
091
789

我想不用迭代,只用一个表达式。我该怎么做?

【问题讨论】:

  • 那么abc的第n个实例应该替换为数组中的第n个索引?
  • 为什么要在没有显式迭代的情况下这样做? (请注意,如果没有任何迭代,就不可能做到这一点 - 在某些时候,您所做或调用的某事会进行一些迭代来解决它。)
  • @Matthew Watson:我喜欢代码短的时候。

标签: c# regex .net-3.5


【解决方案1】:

这是一个“单一表达式版本”:

编辑: 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

【讨论】:

  • 不要在Replace里面使用foreach? :)
  • @Backs 它确实在内部循环,但据我所知,没有循环就无法完成这项任务......
  • 我很确定 op 意味着避免任何他自己编写的循环代码。例如。对于,foreach,Linq...
  • @CSharpie,您能否详细说明m => replaces[index++] 部分?
  • @CSharpie 好吧,老实说,我的代码没有循环,只有“功能样式”。所以你使用正则表达式,我没有。但根据条件,两种解决方案都是错误的。
【解决方案2】:

不用迭代,只用一个表达式

此示例使用静态 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)",   // 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 代表

而我仅限于 3.5。

Regex.Replace(data, "(abc)",  delegate(Match match) { return replacements.Dequeue(); } )

【讨论】:

  • @Pablo 为 .Net 3.5 更新。
猜你喜欢
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多