1

This is my regex. I want to find the opening and closing parentheses and replace them with "\(" and "\)".

word = word.replaceAll(Pattern.quote("("), "\\" + "(").replaceAll(Pattern.quote(")"), "\\" + ")");

This is the output if word = "word)":

New word is: word)

As you can see it didn't change a thing.

Eymeric G
  • 53
  • 7
  • 1
    Why do you need to use regular expressions for a simple replacement like this? Just use the normal replace function and spare yourself some trouble: `word.replace("(", "\\" + "(").replace(")", "\\" + ")");` – OH GOD SPIDERS Oct 09 '17 at 09:24
  • Thank you it worked. You can put this in answer :) – Eymeric G Oct 09 '17 at 09:25

2 Answers2

1

Try to use \\\\ like this :

word = word.replaceAll(Pattern.quote("("), "\\\\" + "(")
        .replaceAll(Pattern.quote(")"), "\\\\" + ")");

or without Pattern.quote :

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

or instead in your case you can just use replace :

word = word.replace("(", "\\(").replace(")", "\\)");
YCF_L
  • 51,266
  • 13
  • 85
  • 129
0

Two answers worked:

word.replace("(", "\\" + "(").replace(")", "\\" + ")"); – OH GOD SPIDERS

and

replacing \\ with \\\\ in the replaceAll - YCF_L.
Szymon Stepniak
  • 36,710
  • 10
  • 91
  • 120
Eymeric G
  • 53
  • 7