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
拉姆達的說明計算重置價值即
請發表您當前的代碼 - 目前尚不清楚你有什麼問題。 –
您是否有要更換的預定義字符串列表?這與簡單地取代循環序列不同,後者可能會耗費大量資源。如果你有一個列表,那麼你可以利用RegularExpressions。 – newb
我確實有預定義的字符串被替換,但這不是問題。預定義的字符串被替換爲[11]或其他。只是它們可能會像[11] [11] [11]一樣反覆出現,在這種情況下,我想通過將它們組合在一起來縮短它[11,3]。希望這是有道理的。 –