Search code examples
javaregexreplaceall

Java Replace One Space Surrounded by Numbers, with Two Spaces


I have the following string:

String line = "367,881 1,092,781  17,819     220   89,905   194,627    342    1,763,575";  

The string has a single space between the first two numbers: 367,881 and 1,092,781. The rest of the numbers are surrounded by more than one space. I would like to add an extra space to the first two numbers only.

Adding two spaces with replace does not work because it adds extra space to the other numbers as well.

line  = line.replace(" ", "  ");

What is a way to achieve adding an extra space to two numbers that are separated by only one space?


Solution

  • You can use following regex:

    String line = "367,881 1,092,781  17,819     220   89,905   194,627    342    1,763,575";
    System.out.println(line.replaceAll("(\\d)\\s(\\d)", "$1  $2"));
    

    Ideone Demo

    This (\\d)\\s(\\d) matches two digits separated by a single space. Since we also need to retain the digits around the spaces while replacing, we can get the capturing groups using $1 etc.