Reputation: 869
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
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
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
OR
String s = "1110000010000";
System.out.println(s.replaceAll("(?<=^(?:\\d{3}|\\d{6}))"," "));
Upvotes: 2