将 C# 中的子字符串与自定义格式相结合? [英] Combining substrings in C# with a custom format?

查看:26
本文介绍了将 C# 中的子字符串与自定义格式相结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Part of an app I'm creating in C# replaces certain substrings in a string with a value in square brackets like [11]. Often there can be the same value straight after - so I want to reduce the amount of text by combining them into one like [11,numberOfSame]

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

For example, if the string contains:
blahblah[122][122][122]blahblahblahblah[18][18][18][18]blahblahblah

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

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

Would anyone know how I would do this? Thanks! :)

推荐答案

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

lambda 的解释:

Explanation of lambda:

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 ]

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

I am using this overload, which accepts a delegate to compute the replacement value.

这篇关于将 C# 中的子字符串与自定义格式相结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆