Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

colon inside a regular expression for javascript

I have a regular expression:

/^([a-zA-Z0-9_ -.''""]+)$/

It works perfectly well allowing alphabets, numbers, and some special characters like -, ., ' and ".

No I want it to allow a colon as well (:). I tried the following regex but it fails - it starts allowing many other special characters.

/^([a-zA-Z0-9_ :-.''""]+)$/

Any idea why?

like image 707
Rajesh Avatar asked Mar 08 '11 19:03

Rajesh


1 Answers

- has a special meaning in character classes, just like in a-z. Try this:

/^([a-zA-Z0-9_ :\-.'"]+)$/

-. (space to dot) allows a few extra characters, like #, $ and more. If that was intentional, try:

/^([a-zA-Z0-9_ -.'":]+)$/

Also, know that you don't have to include any character more than once, that's pretty pointless. ' and " appeared twice each, they can safely be removed.

By the way, sing a colon appears after the dot in the character table, that regex isn't valid. It shouldn't allow extra characters, you're suppose to get an error. In Firefox, you get: invalid range in character class.

like image 130
Kobi Avatar answered Oct 05 '22 13:10

Kobi