2014-06-06 246 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) –

相關問題