0

I tried many variants of different solutions explained here

How to add space on both sides of a string in Java

Regex add space between all punctuation

Add space after capital letter

As well as other ones regarding parenthesis (and many more)

Regex to match parenthesis

I have a String and I simply want this : hi()

To become this : hi ( )

What I have tried so far :

if (phrase.matches("^.*[(].*$")){
            phrase.replaceAll("\\(", " \\( ");
        }

The if works fine but the replaceAll doesn't do anything.

I read online that I might need to put the previous values in the replaceAll so I tried the following

if (phrase.matches("^.*[(].*$")){
    phrase.replaceAll("(.*)\\(", " \\( ");
}

As well as this

    if (phrase.matches("^.*[(].*$")){
    phrase.replaceAll("(.*)\\(", "(.*) \\( ");
}

And this

if (phrase.matches("^.*[(].*$")){
        phrase.replaceAll("(.*)\\((.*)", "(.*) \\( (.*)");
    }

At this point I feel that I am just trying random stuff and I'm missing something trivial here.

Maude
  • 512
  • 3
  • 8
  • 23
  • [See this](https://regex101.com/r/TSv6V1/2). Regex: `\(`; Replace ` ( ` – ctwheels Oct 04 '17 at 17:48
  • Single backslash doesn't work in Java. The equivalent is \\ or  \' or \" and I tried them all – Maude Oct 04 '17 at 17:51
  • From the link above, if you go to the code generator section and select java, you'll get this page: https://regex101.com/r/TSv6V1/2/codegen?language=java. What I posted above in the comment is the pure regex. You need to escape the characters in Java thereafter (as the link in this comment shows) – ctwheels Oct 04 '17 at 17:52

2 Answers2

1

replaceAll doesn't mutate the string. Try

if (phrase.matches("^.*[(].*$")){
    System.out.println(phrase.replaceAll("\\(", " \\( "));
    // => f ( )
}

or

if (phrase.matches("^.*[(].*$")){
    phrase = phrase.replaceAll("\\(", " \\( "));
}
Alejandro C.
  • 3,771
  • 15
  • 18
0

In java, Strings are immutable. So you might want to assign the replaceAll result to a variable.

phrase = phrase.replaceAll("\\(", " (");

Also your if condition can be omitted, cause the replaceAll will replace the strings, only if it finds a match.