Rohan More
Rohan More

Reputation: 131

regex returning true even if comma is not enclosed in double quotes

Below is my regular expression.

/^\\"[a-zA-Z0-9!#\$%&\\'\*\+-\/=\?\^_`{\|}~;,:<>()@\[\]]*\\"$/

It is working correctly apart from the fact that it is returning true even if comma is not included in double quotes. Why is it showing odd behaviour for a comma.

Eg a:b without quotes returns false while a,b without quotes returns true.

Experts can you please help

Upvotes: 0

Views: 94

Answers (1)

stema
stema

Reputation: 93006

Because you are creating a character range here :

/^\\"[a-zA-Z0-9!#\$%&\\'\*\+-\/=\?\^_`{\|}~;,:<>()@\[\]]*\\"$/
                          ^^^^^

This means all characters from + to /, this includes also the ,.

INside a character class, you don't need to escape the normal regex special characters, but there is another one, that get a special meaning the -.

So the correct character class would be

/^\\"[a-zA-Z0-9!#$%&\\'*+\-\/=?^_`{\|}~;,:<>()@\[\]]*\\"$/

The alternative would be to put the - at the start or the end of the character class, in that cases it would not create a range and does not need escaping.

Upvotes: 3

Related Questions