-1

I am attempting to replace a white space in a string that occurs before a closing parentheses or after an opening parantheses.

For example the string "8 / ( 1 + 3 ) - 6 ^ 2"

Should be changed to: "8 / (1 + 3) - 6 ^ 2"

I am assuming this will use the replaceAll method but I'm unfamiliar with how to use this expression properly for my specific scenario.

Thanks a lot for your help.

  • Just to be pedantic: you can't replace any characters in a Java string. Strings are immutable. You always have to remember to save (assign) the new string that's created, or you'll end up losing the changes. – markspace Apr 14 '20 at 04:58

1 Answers1

1

Parenthesis (open and close) are special characters in a regular expression. So you must escape them with \, which is also a special character in general in Java, so you must escape that with another \. Despite how odd it looks, you want something like

String s = "8 / ( 1 + 3 ) - 6 ^ 2";
System.out.println(s.replaceAll("\\(\\s*", "(").replaceAll("\\s*\\)", ")"));

which will first replace all open parens followed by any number of whitespace with just open parens. Then it replaces any number of whitespace and a close parens with just close parens. Outputs (as requested)

8 / (1 + 3) - 6 ^ 2
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    @Cyclone You're welcome. Just note `\\s*` matches any number (including zero) whitespace characters. Which is fine here, but may not be fine everywhere. If you want at least one (or more) use `\\s+` – Elliott Frisch Apr 14 '20 at 04:26