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 pattern will also match the comma (­,), that is, 0x2C, and DOT (.), that is, 0x2E, characters.

An unescaped hyphen can be safely used at the first or last positions in a character class to avoid making a range. With that in mind, we can correct this character class by using any of the following forms:

[-*+/] 
[*+/-] 
[*+-/] 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.68.18