c0nf1ck c0nf1ck - 5 months ago 7
Java Question

Split a string into pieces using java / a better code

I have to split this string:

00016282000079116050


It has predefined chunks. Should be just like that:

00016 282 00 0079 116 050


I made this code:

String unformatted = String.valueOf("00016282000079116050");
String str1 = unformatted.substring(0,5);
String str2 = unformatted.substring(5,8);
String str3 = unformatted.substring(8,10);
String str4 = unformatted.substring(10,14);
String str5 = unformatted.substring(14,17);
String str6 = unformatted.substring(17,20);

System.out.println(String.format("%s %s %s %s %s %s", str1, str2, str3, str4, str5, str6));


It works, but I need to make this code more presentable/prettier.

Something with Java 8 streams or regex should be good. Any suggestions?

Answer

You could use a regular expression to compile a Pattern with 6 groups, something like

String unformatted = "00016282000079116050"; // <-- no need for String.valueOf
Pattern p = Pattern.compile("(\\d{5})(\\d{3})(\\d{2})(\\d{4})(\\d{3})(\\d{3})");
Matcher m = p.matcher(unformatted);
if (m.matches()) {
    System.out.printf("%s %s %s %s %s %s", m.group(1), m.group(2), m.group(3), 
            m.group(4), m.group(5), m.group(6));
}

Outputs (as requested)

00016 282 00 0079 116 050

Or, as pointed out in the comments, you could use Matcher.replaceAll(String) like

if (m.matches()) {
    System.out.println(m.replaceAll("$1 $2 $3 $4 $5 $6"));
}