Do not use an unescaped hyphen in the middle of a character class

We know that most of the special regex metacharacters are treated literally inside the character class and we do not need to escape them inside the character class. However, if an unescaped hyphen is used between two characters, then it makes it a range between the previous and the next character of the hyphen.

As an illustrative example, let's consider this character class expression to match the four basic math operators, +,-,*,/:


The way it is written, this character class has a hyphen between the + and / characters. This makes the character class match all the characters that fall between + (0x2A) and / (0x2F), as per the ASCII table. Due to this reason, the preceding ...

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.