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 books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.