4

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?

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't know why yours got downvoted. Looks correct to me. +1
0

use line=line.replaceFirst("\\s"," ")

Comments

0

This should do it, using the word boundary metacharacter (\b):

line = line.replaceAll("\\b \\b", "  ");

This only works on the assumption that you don't have cases where there are non-numbers (e.g. letters) separated by a single space in your string. If you do happen to also have letters, the solution proposed by AKS is more correct.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.