pseudorandom
pseudorandom

Reputation: 267

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?

Upvotes: 4

Views: 463

Answers (3)

Robby Cornelissen
Robby Cornelissen

Reputation: 97130

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.

Upvotes: 0

AKS
AKS

Reputation: 19811

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.

Upvotes: 6

Khan Abdulrehman
Khan Abdulrehman

Reputation: 854

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

Upvotes: 0

Related Questions