user1768615
user1768615

Reputation: 281

How to add spaces between numbers in string with word and integer?

Having string like this

"APM35 2FAST4YOU -5ABBA STEVE0.5&Tom"

and using regular expression Im not getting result as I want to. How can I add space before and after of each integer? Code:

String s = "APM35 2FAST4YOU -5ABBA STEVE0.5&Tom";
s = s.replaceAll("(\\d)([A-Za-z])", "\\1 \\2");
System.out.println(s);

I'm getting such result:

APM35 1 2AST1 2OU -1 2BBA STEVE0.5&Tom

and I'd like get this string as result:

APM 35 2 FAST 4 YOU -5 ABBA STEVE 0.5 &Tom

Upvotes: 0

Views: 5934

Answers (4)

infthi
infthi

Reputation: 557

Try this:

s.replaceAll("([^\\d-]?)(-?[\\d\\.]+)([^\\d]?)", "$1 $2 $3").replaceAll(" +", " ");

First regexp can generate some extra spaces, they are removed by second one.

Upvotes: 2

assylias
assylias

Reputation: 328598

You could do it in two steps:

String s = "APM35 2FAST4YOU -5ABBA STEVE0.5&Tom";
//add a space after the numbers
String step1 = s.replaceAll("(-?\\d\\.?\\d*)([^\\d\\s])", "$1 $2");
//add a space before the numbers
String step2 = step1.replaceAll("([^0-9\\-\\s])(-?\\d\\.?\\d*)", "$1 $2");

Upvotes: 4

Djon
Djon

Reputation: 2260

Sorry I wrote too fast, but I might as well ask: are you sure Java's regex API is able to identify a group (\1 and \2)?

Because it seems that parts of the string are replaced by actual 1s and 2s so this might not be the correct syntax.

(And it seems that you are only checking for numbers followed by text, not the other way arround.)

Upvotes: 0

Quurks
Quurks

Reputation: 53

You could use the expression "(-?[0-9]+(\.[0-9]+)?)"

(0.5 is no integer, if you only want integers (-?[0-9]+) should be enough)

and replace it with " \1 " or " $1 " (Dont know which is the right one for Java) (Spaces before and after)

Upvotes: 0

Related Questions