Escaping special regex metacharacters and escaping rules inside the character classes

We know that . matches any character, [ and ] are used for character classes, { and } are used for limiting quantifiers, and ? , *, and + are used for various quantifiers. To match any of the metacharacters literally, one needs to escape these characters using a backslash (\ ) to suppress their special meaning. Similarly, ^ and $ are anchors that are also considered regex metacharacters.

Let's see some examples of escaping metacharacters in regular expressions.

The following regex matches the string, a.b?:

     a\.b\? 

The following regex matches the string, {food}:

    \{food\} 

The following regex matches the string, abc:][}{:

    abc:\]\[\}\{ 

The following regex ...

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.