3

I have strings in the format below, which need to be transformed to:

4ABC3D -> AAAABCDDD

ABCD2F -> ABCDFF

Basically the number shows how many times the next character should be repeated. I'm using C# and regex.Replace() method, but I'm not sure how to repeat the character captured by Group 1 a number of times, captured in Group 2:

string inputString = "4ABC3D";
Regex regex = new Regex("([0-9]+)([A-Z])");
inputString = regex.Replace(inputString, "$1{$2}"); 
//returns 4{A}BC3{D}

Any help is appreciated :)

Pokemon
  • 63
  • 1
  • 6
  • http://stackoverflow.com/questions/411752/best-way-to-repeat-a-character-in-c-sharp this might help since you have all other things necessary – gaganso May 30 '16 at 15:19

1 Answers1

2

Use a callback or lambda to build the replacement pattern based on the data captured with your regex:

var inputString = "4ABC3D";
var res = Regex.Replace(inputString, "([0-9]+)([A-Z])",
    x => String.Concat(Enumerable.Repeat(x.Groups[2].Value, Int32.Parse(x.Groups[1].Value)))
); // => AAAABCDDD

See the IDEONE demo

Note that it is safe to use Int32.Parse since [0-9]+ is sure to capture at least 1 digit.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397