2012-11-30 49 views
0

我在C#中創建的應用程序的一部分將替換字符串中的某些子字符串,並將其替換爲方括號中的值,例如[11]。通常可以有相同的值後直 - 所以我想將它們組合成一個像[11,numberOfSame]C#中的子字符串與自定義格式?

例如,減少文字量,如果字符串包含:
blahblah[122][122][122]blahblahblahblah[18][18][18][18]blahblahblah

所需的新的字符串會是:
blahblah[122,3]blahblahblahblah[18,4]blahblahblah

有人會知道我該怎麼做嗎?謝謝! :)

+2

請發表您當前的代碼 - 目前尚不清楚你有什麼問題。 –

+0

您是否有要更換的預定義字符串列表?這與簡單地取代循環序列不同,後者可能會耗費大量資源。如果你有一個列表,那麼你可以利用RegularExpressions。 – newb

+0

我確實有預定義的字符串被替換,但這不是問題。預定義的字符串被替換爲[11]或其他。只是它們可能會像[11] [11] [11]一樣反覆出現,在這種情況下,我想通過將它們組合在一起來縮短它[11,3]。希望這是有道理的。 –

回答

2
Regex.Replace("blahblah[122][122][122]blahblahblahblah[18][18][18][18]blahblahblah", 
    @"(\[([^]]+)])(\1)+", 
    m => "[" + m.Groups[2].Value + "," + (m.Groups[3].Captures.Count + 1) + "]") 

返回:

blahblah[122,3]blahblahblahblah[18,4]blahblahblah 

正則表達式的說明:

m =>        Accepts a Match object 
"[" +        A [ 
m.Groups[2].Value +     Whatever was in group 2 
"," +        A , 
(m.Groups[3].Captures.Count + 1) + The number of times group 3 matched + 1 
"]"         A ] 

我使用this overload,其接受委託:

(   Starts group 1 
    \[  Matches [ 
    (  Starts group 2 
    [^]]+ Matches 1 or more of anything but ] 
)   Ends group 2 
    ]   Matches ] 
)   Ends group 1 
(   Starts group 3 
    \1  Matches whatever was in group 1 
)   Ends group 3 
+   Matches one or more of group 3 

拉姆達的說明計算重置價值即

+0

+1。你可以把它改成'... +(m.Groups [3] .Captures.Count == 0?「」:「,」+(m.Groups [3] .Captures.Count + 1))+ .. 。「以避免添加」1「計數。 –

+0

@ OlivierJacot-Descombes仔細看看我的正則表達式。 –

+0

哦,「+」是這樣做的。我的錯誤! –

1
string input = "[122][44][122]blah[18][18][18][18]blah[122][122]"; 
string output = Regex.Replace(input, @"((?<firstMatch>\[(.+?)\])(\k<firstMatch>)*)", m => "[" + m.Groups[2].Value + "," + (m.Groups[3].Captures.Count + 1) + "]"); 

返回:

[122,1][44,1][122,1]blah[18,4]blah[122,2] 

說明:

(?<firstMatch>\[(.+?)\])匹配的[123]集團,名團firstMatch

\k<firstMatch>任何文本是由firstMatch組匹配的比賽和添加*匹配零次或多次,給我們在lambda中使用的計數。

我的任何東西正則表達式參考:http://www.regular-expressions.info/