0

I am trying to write a java regex to add white space between character and number. I tried few of them but its not working.

For example: This string "FR3456", I would like this to be converted to "FR 3456".

Any help will be appreciated.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
sgamer
  • 73
  • 1
  • 4
  • 13
  • 3
    Showing us the regex that you used to attempt to solve this would go a long way into helping; we could potentially build off of that. – Makoto Aug 10 '14 at 16:58
  • This might help you -> http://stackoverflow.com/questions/8270784/how-to-split-a-string-between-letters-and-digits-or-between-digits-and-letters – Xerath Aug 10 '14 at 17:01

1 Answers1

11

You can add a space between non-digit and digit using Positive Lookbehind & Lookahead

System.out.println("FR3456".replaceAll("(?<=\\D)(?=\\d)"," "));

Here

\D  A non-digit: [^0-9]
\d  A digit: [0-9]

for more info have a look at Java Regex Pattern


Or use (?<=[^0-9])(?=[0-9])

Here is online demo

Pattern explanation:

  (?<=                     look behind to see if there is:
    [^0-9]                   any character except: '0' to '9'
  )                        end of look-behind
  (?=                      look ahead to see if there is:
    [0-9]                    any character of: '0' to '9'
  )                        end of look-ahead
Braj
  • 46,415
  • 5
  • 60
  • 76
  • How to get results like `FR 3 4 5 6` ? – Qamar Feb 28 '19 at 12:03
  • Thanks for explanation use `(?<=\S)(?=\d)` to get results like `FR 3 4 5 6`, – Qamar Feb 28 '19 at 12:09
  • how to get result like **765 Xyz 987** for **765Xyz987** , **765 Xyz** for **765Xyz**, and **Xyz 987** for **Xyz987**. If possible a common command maybe? If not, separate command. – OnePunchMan Mar 30 '19 at 10:00
  • 1
    @OnePunchMan you can try `"765Xyz987".replaceAll("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"," ")` that means any non-digit followed by digit or any digit followed by non-digit – Braj Mar 30 '19 at 14:20