1

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?

3
  • 1
    what's your expected output if the input is, 111000001000 ? Commented Dec 30, 2014 at 15:50
  • @Todd No parsing is required, though the given string is always numbers by nature but only thing I care is to insert a space after first 3 and a space after another 3 Commented Dec 30, 2014 at 16:03
  • @AvinashRaj 111000001000 => 111 000 001000 Commented Dec 30, 2014 at 16:04

2 Answers 2

6

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

str = str.replaceFirst("(...)(...)", "$1 $2 ");
Sign up to request clarification or add additional context in comments.

3 Comments

@AvinashRaj When I read the question, I think that is exactly, what OP wants. If he needs something else, it would be good to give more examples and/or a better specification...
don't know, so i asked it to the op.
It looks like prefect case for replaceFirst instead of replaceAll. Not that it will improve performance but readability of code :)
2

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}))"," "));

6 Comments

I actually don't think this is what OP wants. If input was "1110001110000" I think OP wants "111 000 1110000" not "111 000 111 0000". Text from OP: a space inserted after the first 3 characters and another space inserted after another 3 characters doesn't mention or imply conditional formatting
@Bohemian no, i think it's not op wants . OP wants all the three digits which is follwed by a three digits would be seperated by spaces.
I think OP should specificy more clearly. Everything else is just guessing. ;)
@brimborium what if the op means for that particular example only?
@brimborium I think it's clear already. I think this answer overbaked it
|

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.