Skip to content

Java RegEx – How to Escape and Match Dot

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.

Output

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.

Output

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.

About the author

Leave a Reply

Your email address will not be published.