regex - Split a string into pieces using java / a better code -


i have split string:

00016282000079116050 

it has predefined chunks. should that:

00016 282 00 0079 116 050 

i made 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, need make code more presentable/prettier.

something java 8 streams or regex should good. suggestions?

you use regular expression compile pattern 6 groups, like

string unformatted = "00016282000079116050"; // <-- no need 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, pointed out in comments, use matcher.replaceall(string) like

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

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -