2014-06-06 189 views
5

在一个字符串中,我试图用不同的值更新同一单词的多个实例。用一个唯一值替换字符串中的每个单词的实例

这是一个过于简单的例子,但鉴于以下字符串:

"The first car I saw was color, the second car was color and the third car was color" 

字的颜色我想用“红”,二审应该是“绿色”和更换的第一个实例第三例应该是“蓝色”。

我想要尝试的是寻找绑定单词的正则表达式模式,通过循环进行交互并逐个替换它们。请参阅下面的示例代码。

var colors = new List<string>{ "reg", "green", "blue" }; 
var sentence = "The first car I saw was color, the second car was color and the third car was color"; 

foreach(var color in colors) 
{ 
    var regex = new Regex("(\b[color]+\b)"); 
    sentence = regex.Replace(sentence, color, 1); 
} 

但是,“颜色”一词永远不会被替换为适当的颜色名称。我找不到我做错了什么。

回答

3

试试比赛代表。

这是Regex.Replace()的一个重载,大多数人都错过了。它只是让你定义一个潜在的上下文敏感的动态处理程序,而不是硬编码的字符串来代替,并且可能有副作用。 “i ++%”是一个模运算符,下面用它来简单循环访问这些值。你可以使用数据库或哈希表或任何东西。

var colors = new List<string> { "red", "green", "blue" }; 
var sentence = "The first car I saw was color, the second car was color and the third car was color"; 
int i = 0; 
Regex.Replace(sentence, @"\bcolor\b", (m) => { return colors[i++ % colors.Count]; }) 

该解决方案适用于任意数量的替换,这是更典型的替换(全局替换)。

+0

这个伎俩。 –

+0

这是一个可爱的代表,我发现你对'regex'标签并不陌生。 :) – zx81

+0

@ zx81:谢谢!是的,根据我的经验,大多数人甚至没有意识到.NET Regex库支持匹配委托。尽管我更喜欢使用regex作为语法而不是API,比如Perl。这是我用可乐实际做的,尽管我还没有决定如何将正则表达式委托语法映射到语法。 – codenheim

1

我尽量远离正则表达式。它有它的地方,但不是简单的情况下,像这样恕我直言:)

public static class StringHelpers 
{ 
    //Copied from http://stackoverflow.com/questions/141045/how-do-i-replace-the-first-instance-of-a-string-in-net/141076#141076 
    public static string ReplaceFirst(this string text, string search, string replace) 
    { 
     int pos = text.IndexOf(search); 
     if (pos < 0) 
     { 
      return text; 
     } 
     return text.Substring(0, pos) + replace + text.Substring(pos + search.Length); 
    } 
} 


var colors = new List<string>{ "red", "green", "blue" }; 
string sentence = colors.Aggregate(
    seed: "The first car I saw was color, the second car was color and the third car was color", 
    func: (agg, color) => agg.ReplaceFirst("color", color)); 
+0

Downvoter,为什么downvote? –

2

的问题是,在你的榜样,color并不总是前面和后面一个非单词字符。为了您的例如,这个工作对我来说:

var regex = new Regex("\b?(color)\b?"); 

所以这样的:

var colors = new List<string>{ "red", "green", "blue" }; 
var sentence = "The first car I saw was color, the second car was color and the third car was color"; 

foreach(var color in colors) 
{ 
    var regex = new Regex("\b?(color)\b?"); 
    sentence = regex.Replace(sentence, color, 1); 
} 

产生以下:

第一辆车我看到的是红色的,第二辆车是绿和第三个 车是蓝色的

+1

'\ b?'是多余的 - 要么是文字边界,要么是不是 - 可能会使用'“(颜色)”' –

+0

就是这样。谢谢! –

+0

@UriAgassi我不会和你争论,我实际上倾向于使用Steven Wexler的[回复](http://stackoverflow.com/a/24089785/1346943) –

相关问题