使用java /更好的代码将字符串拆分成多个部分

时间:2016-06-10 23:46:28

标签: java regex

我必须拆分这个字符串:

00016282000079116050

它有预定义的块。应该就是这样:

00016 282 00 0079 116 050

我制作了这段代码:

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));

它有效,但我需要让这段代码更具代表性/更漂亮。

使用Java 8流或正则表达式的东西应该是好的。有什么建议吗?

3 个答案:

答案 0 :(得分:9)

您可以使用正则表达式来编译具有6个组的Pattern,类似于

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));
}

输出(根据要求)

00016 282 00 0079 116 050

,正如评论中指出的那样,您可以使用Matcher.replaceAll(String)之类的

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

答案 1 :(得分:4)

更面向的方法是使用循环和预定长度的数组。

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]) + " ");
}

输出

00016 282 00 0079 116 050 

答案 2 :(得分:0)

        String unformatted = "00016282000079116050";
        int[] splittingPoints = new int[]{5,3,2,4,3,3};
        int charactersProcessed = 0;
        int howManyBeforeSplit = 0;
        int chunksDone = 0;
        for (char c : unformatted.toCharArray()) {
            if ((charactersProcessed++ - chunksDone) == splittingPoints[howManyBeforeSplit]) {
                System.out.print(" ");
                chunksDone += splittingPoints[howManyBeforeSplit++];
            }
            System.out.print(c);
        }