Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace special characters and numbers with the character and spaces on each side

So basically I'm trying to convert this string: "(1+2) / 2" to this "( 1 + 2 ) / 2". And I've tried this:

String inputInfix = input.replaceAll("[^0-9/]", " [^0-9/] ");

But it doesn't work, is there some way to replace every character except "/" and the digits with a space on either side. For example, "(1 / 2)" -> " ( 1 / 2 )"

like image 933
Xanthan Avatar asked Dec 05 '25 09:12

Xanthan


1 Answers

You can use

input.replaceAll("(?<=[^\\s/])(?=[^\\s/])", " ")

See the regex demo. Details:

  • (?<=[^\s/]) - a positive lookbehind that matches a location that is immediately preceded with a char other than a whitespace char and a slash
  • (?=[^\s/]) - a positive lookahead that matches a location that is immediately followed with a char other than a whitespace char and a slash.
like image 200
Wiktor Stribiżew Avatar answered Dec 06 '25 23:12

Wiktor Stribiżew