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 ...

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.