Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string into pieces using java / a better code

Tags:

java

regex

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?

like image 811
c0nf1ck Avatar asked Dec 10 '22 16:12

c0nf1ck


2 Answers

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"));
}
like image 95
Elliott Frisch Avatar answered Dec 13 '22 04:12

Elliott Frisch


A more java oriented way would be to use a loop and an array of predefined lengths.

int[] lims = {5,3,2,4,3,3};
int total = 0;
String original = "00016282000079116050";

for (int i = 0 ; i < lims.length ; i++) {
    System.out.print(original.substring(total, total+=lims[i]) + " ");
}

Output

00016 282 00 0079 116 050 
like image 24
Yassin Hajaj Avatar answered Dec 13 '22 05:12

Yassin Hajaj