O'Reilly logo

Java 9 Regular Expressions by Anubhava Srivastava

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Double escaping in a Java String when defining regular expressions

In Java, all the regular expressions are entered as a String type, where \ acts as an escape character and is used to interpret certain special characters such as \t, \n, and so on. So, it is necessary to double-escape all the predefined classes, such as \w, \d, \s, using two backslashes and while escaping metacharacters, such as \[, \(, \+, and so on, in string literals.

If we have to use the preceding regex for a dollar amount in Java, then it would be as follows:

final String re = "\\$\\d+\\.\\d+";

The preceding example that matches a signed decimal number has to be written as follows in Java:

final String re = "^[+-]?\\d*\\.?\\d+$";

For the same reasons, if we have ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required