Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add character into middle of String

Tags:

java

regex

I need your help to turn a String like 12345678 into 1234.56.78

[FOUR DIGITS].[TWO DIGITS].[TWO DIGITS]

My code:

String s1 = "12345678";
s1 = s1.replaceAll("(\\d{4})(\\d+)", "$1.$2").replaceAll("(\\d{2})(\\d+)", "$1.$2");
System.out.println(s1);

But the result is 12.34.56.78

like image 387
Matías W. Avatar asked Feb 05 '23 08:02

Matías W.


1 Answers

If you are sure that you'll always have the input in the same format then you can simply use a StringBuilder and do something like this:

String input = "12345678";
String output = new StringBuilder().append(input.substring(0, 4))
        .append(".").append(input.substring(4, 6)).append(".")
        .append(input.substring(6)).toString();
System.out.println(output);

This code creates a new String by appending the dots to the sub-strings at the specified locations.

Output:

1234.56.78
like image 156
user2004685 Avatar answered Feb 08 '23 14:02

user2004685