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

Avoid escaping every non-word character

Some programmers overdo escaping, thinking that they need to escape every non-word character such as colon, hyphen, semicolon, forward slash, and whitespace, which is not correct. They end up writing a regular expression as follows:

^https?\:\/\/(www\.)?example\.com$ 

The preceding regex pattern uses excessive escaping. This pattern still works, but it is not very readable. The colon and forward slash have no special meaning in regex; hence, it is better to write this regex in the following way:

^https?://(www\.)?example\.com$ 

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