When using RegEx in Java you might need to treat one or more metacharacters as ordinary characters. As a reminder, the metacharacters in a Java RegEx are:

([{^$|)?*+.

If you want to treat them as ordinary characters you have two options:

  1. Escape the metacharacter with a backslash,
  2. Enclose the whole string that contains metacharacters within Q and E

Q means: “quotes all characters until E”, while E ends the quotes.

The following example should help clarify the subject:

String test = "I want to replace the . with the ,";
String replaced = test.replaceAll(".", ",");
System.out.println(replaced);

What do you expect the method above to do? Do you think the following string will be displayed?

I want to replace the , with the ,

If so, you might be surprised to find out that what you actually get is:

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

The problem is that the replaceAll method of the String class accepts a RegExp as its first parameter. Since . means any character, writing test.replaceAll(".", ","); translates to: “Replace ANY character of the test string with a comma”. As I said previously you can fix that in two ways. Either escape the dot with a backslash or enclose it within Q and E. What I didn’t mention is that, since the backslash is itself a metacharacter, you need to escape it too. :-)

Translating this into Java you have:

test.replaceAll("\.", ",");
test.replaceAll("\Q.\E", ",");

I prefer to use the first method when there is only one metacharacter. However, when I have several metacharacters or I don’t know at compile time what my string is going to be, I use the second method.