Java-简单有效的String formate方法

时间:2019-01-31 09:36:33

标签: java

我想将以下字符串格式化为特定格式,

String str ="BBA987462HBBA84536BBA647232K"; // This is dynamic value

输出:(应该)

Str [] = {"BBA 987 46 2 H", "BBA 845 36", "BBA 647 23 2 K"}

此处BBA是分离器,格式为“ BBA XXX XX X H”。 (X号)。

注意:BBA仅是常数。 所需格式:“ BBA XXX XX X H”

3 个答案:

答案 0 :(得分:2)

使用正则表达式

  • SELECT * FROM Users WHERE UserID = @UserID OR (UserID IS NULL AND @UserID IS NULL); 找到一个方块
  • BBA\d{1,7}H?拆分一个区块

你会得到的

(?<=BBA)|(?<=BBA\d{3})|(?<=BBA\d{5})|(?<=BBA\d{6})

答案 1 :(得分:0)

public static void main(String[] args){
    String str ="BBA987462HBBA84536BBA647";
    String[] ans = str.split("BBA");
    for(String s:ans){
        if(s.length()==7){
            System.out.println("BBA "+s.substring(0, 3)+" "+s.substring(3,5)+" "+s.substring(5, 6)+" "+"H");
        }
        else if(s.length()==5){
            System.out.println("BBA "+s.substring(0, 3)+" "+s.substring(3,5));
        }
        else if(s.length()==3){
            System.out.println("BBA "+s.substring(0, 3));
        }
    }
}

答案 2 :(得分:0)

因此,假设格式始终保持相同的“ BBA XXX XX X H”,而您想从中获得最长的序列 你可以做类似的事情

public static String[] splitBBA(String input) {
    String[] bbas = input.split("BBA"); //split text by "BBA"
    for(int i = 0; i < bbas.length; i++) { //loop through array of BBA strings
        System.out.println(bbas[i]);
        //split up the current BBA string based on its length
        if(bbas[i].length() >= 7) { //
            bbas[i] = bbas[i].substring(0, 3) + " " + bbas[i].substring(3, 5) + " " + bbas[i].substring(5, 6) + " " + bbas[i].substring(6, bbas[i].length());
        }else
        if(bbas[i].length() >= 5) {
            bbas[i] = bbas[i].substring(0, 3) + " " + bbas[i].substring(3, 5) + " " + bbas[i].substring(5, bbas[i].length());
        }else if(bbas[i].length() >= 3){
            bbas[i] = bbas[i].substring(0, 3) + " " + bbas[i].substring(3, bbas[i].length());
        }
        System.out.println(bbas[i]);
        bbas[i] = "BBA " + bbas[i]; //add BBA to the front, because "split("BBA") removes the "BBA" at the front
    }
    String[] result = new String[bbas.length-1];
    for(int i = 0; i < result.length; i++) {
        result[i] = bbas[i+1];
    }
    return result; //output is [BBA 987 46 2 H, BBA 845 36 , BBA 647]
}