Escaping inside a character class

In the Java regex engine, all the special regex metacharacters lose their special meaning inside a character class except the ^ (carrot), - (hyphen), ] (right square bracket), and \ (backslash) characters.

Inside a character class, the hyphen also does not need to be escaped when used as the first or last character, since a character range requires both the left-hand side and the right-hand side characters. Similarly, ^ (carrot) needs to escaped only when used as the first character inside a character class.

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.