Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing the number with the number of spaces

Tags:

java

I have a String:

String example = "AA5DD2EE3MM";

I want to replace the number with the number of spaces. Example:

String example = "AA     DD  EE   MM"

If the String would be

String anotherExample = "a3ee"

It should turn into:

String anotherExample = "a   ee"

I want to do it for any string. Not only for the examples above.

like image 703
dodododo97 Avatar asked Dec 13 '22 06:12

dodododo97


1 Answers

Split your input at digit and non digit chars as a stream, map digits to the corsponding number of spaces using String.repeat, collect to string using Collectors.joining():

String input  = "AA5DD2EE3MM";
String regex  = "(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)";
String result = Pattern.compile(regex)
                        .splitAsStream(input)
                        .map(s -> s.matches("\\d+") ? " ".repeat(Integer.parseInt(s)) : s)
                        .collect(Collectors.joining());
like image 54
Eritrean Avatar answered Dec 15 '22 20:12

Eritrean