Java RegEx – How to Escape and Match Dot example shows how to escape and match a dot (.) literally in Java regular expression pattern.
How to match a dot using regex in Java?
There are some characters that have a special meaning in the regular expressions. These characters are called metacharacters. The dot (“.”) is one of them. When used in the regular expression, it matches any character.
This creates a problem when we want to match a dot with a literal dot instead of any character. The most common problem comes when we split a string using the split method or try to replace it using the replaceAll method. Please see below example to understand it.
1 2 3 4 5 6 7 8 9 10 |
package com.javacodeexamples.regex; public class RegExEscapeDot { public static void main(String[] args) { String str = "Hello.World"; System.out.println("String is: " + str.replaceAll(".", "")); } } |
Output
1 |
String is: |
As you can see from the output, the replaceAll method replaced everything with an empty string instead of just a dot. It is because the dot matches with anything.
To match a dot literally, we need to escape it. The escaping is done by “\”. But since the regex patterns are defined using strings, we need to escape backspace itself with another backslash character. So basically, whenever we need to match the dot character literally, we need to use “\\.” instead of the “.” character.
Let’s run the same example using the escaped dot this time.
1 2 3 4 5 6 7 8 9 10 |
package com.javacodeexamples.regex; public class RegExEscapeDot { public static void main(String[] args) { String str = "Hello.World"; System.out.println("String is: " + str.replaceAll("\\.", "")); } } |
Output
1 |
String is: HelloWorld |
As you can see from the output, this time it worked as intended, and the dot was matched literally.
If you want to learn more about the regex, please visit the Java RegEx tutorial.
Please let me know your views in the comments section below.