Search code examples
javaregexstringreplacereplaceall

Replace the specific text between curley braces with java regx


I need to replace the {0} with "D1" , {1} with "X0" , {2} with "DP12001" and so on... I tried to write with regex and it was like this.

    String header = "{0}^{1}^{2}^{3}^{4}^{5}^{6}^{7}^{8}^{9}^{10}";
    String _header = "";
    String rl = "D1,X0,DP12001,1,2,10021521012,1,141128135639,1,12,0";
    logger.debug("rl-->{}", rl);
    String[] parts = rl.split(",");
    int partCount = 0;
    for (String part : parts) {
        _header = header.replaceAll("\\{." + partCount + "\\}", part);
        partCount++;
    }

I need the final output like this. "D1^X0^DP12001^1^2^10021521012^1^141128135639^1^12^0"

but my code is not work as expected.


Solution

  • You could use MessageFormat here:

    String header = "{0}^{1}^{2}^{3}^{4}^{5}^{6}^{7}^{8}^{9}^{10}";
    String rl = "D1,X0,DP12001,1,2,10021521012,1,141128135639,1,12,0";
    String[] parts = rl.split(",");
    System.out.println(MessageFormat.format(header, parts));
    

    (live demo)