Kaizar Laxmidhar
Kaizar Laxmidhar

Reputation: 869

java regex pattern to format number with space

I have number

1110000010

that's need to be formatted so that there is a space inserted after the first 3 characters and another space inserted after another 3 characters so that it looks like:

111 000 0010 

What's the simple java regex pattern to achieve this?

Upvotes: 1

Views: 1391

Answers (2)

Bohemian
Bohemian

Reputation: 424983

If it's only 2 spaces you need, capture the 2 groups and write them back out with spaces:

str = str.replaceFirst("(...)(...)", "$1 $2 ");

Upvotes: 6

Avinash Raj
Avinash Raj

Reputation: 174696

Use capturing groups and a positive lookahead assertion like below.

String s = "1110000010";
System.out.println(s.replaceAll("(\\d{3})(?=\\d{3})","$1 "));

The above regex would capture the three digits only if it's followed by three digits.

Output:

111 000 0010

DEMO

OR

String s = "1110000010000";
System.out.println(s.replaceAll("(?<=^(?:\\d{3}|\\d{6}))"," "));

Upvotes: 2

Related Questions