0

我在 C# 中创建的应用程序的一部分将字符串中的某些子字符串替换为方括号中的值,例如[11]. 通常之后可以有相同的值 - 所以我想通过将它们组合成一个来减少文本的数量[11,numberOfSame]

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

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

有人知道我会怎么做吗?谢谢!:)

4

2 回答 2

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

正则表达式的解释:

(           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

λ的解释:

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 ]

我正在使用这个重载,它接受一个委托来计算替换值。

于 2012-12-03T15:49:18.263 回答
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/

于 2012-12-03T16:18:48.270 回答