db1975 db1975 - 7 months ago 8
Java Question

How can I format a string in java "012df3g4h5j6 78" => "01 23 45 67 8"

I want to format a string with numbers and other characters:
Sample:


input => output


  • "012df3g4h5j6 78" => "01 23 45 67 8"

  • "012df3g4h5j6 7" => "01 23 45 67"

  • "012 3 45 6 78" => "01 23 45 67 8"

  • "012 3 45 6" => "01 23 45 6"



I have a solutions only for numbers:


  • "012345678" => "01 23 45 67 8"

  • "01234567" => "01 23 45 67"

  • "01234567" => "01 23 45 67"



regexp = "(?=[0-9]{2})(([0-9]){2})"

replacement = "$1 "

Answer

Try this

(\D*)(\d)(?:(\n)|(\D*)(\d)(\n?))

Regex demo

Or

(\D*)(\d)(?:(\n|$)|(\D*)(\d)((?:\n|$)?))

Demo

Explanation:
( … ): Capturing group sample
\: Escapes a special character sample
*: Zero or more times sample
(?: … ): Non-capturing group sample
|: Alternation / OR operand sample
?: Once or none sample

Input:

012df3g4h5j6 78
012df3g4h5j6 7
012 3 45 6 78
012 3 45 6
012345678
01234567
01234567

Output

01 23 45 67 8 
01 23 45 67 
01 23 45 67 8 
01 23 45 6 
01 23 45 67 8 
01 23 45 67 
01 23 45 67 
Comments