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]
For example, if the string contains:
blahblah[122][122][122]blahblahblahblah[18][18][18][18]blahblahblah
The desired new string would be:
blahblah[122,3]blahblahblahblah[18,4]blahblahblah
Would anyone know how I would do this? Thanks! :)
Returns:
Explanation:
(?<firstMatch>\[(.+?)\])
Matches the [123] group, names group firstMatch\k<firstMatch>
matches whatever text was that was matched by the firstMatch group and adding * matches it zero or more times, giving us our count used in the lambda.My reference for anything Regex: http://www.regular-expressions.info/
Returns:
Explanation of regex:
Explanation of lambda:
I am using this overload, which accepts a delegate to compute the replacement value.