Search code examples
javastringcomparespace

How to add spaces between number and word in a string in Java?


i have a lot of string which contains also number like : LOD140IXAL COMP 1X240GG

I would like to put whitespace between numbers and word if there isn't. the number could be every where in the string.


Solution

  • One way to do this is using regular expressions. Replacing the following monster with a single space should do the trick:

    "(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])"
    

    When applied to your example (LOD140IXAL COMP 1X240GG), it produces LODIXAL COMP 1 X 240 MG.

    In a nutshell, the regex looks for a letter immediately followed by a digit, or a digit immediately followed by a letter, and inserts a space between them. To achieve this, it uses zero-width assertions (lookahead and lookbehind).