Rajesh
Rajesh

Reputation: 53

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?

Upvotes: 5

Views: 8279

Answers (3)

Kobi
Kobi

Reputation: 138037

- 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.

Upvotes: 8

codaddict
codaddict

Reputation: 455132

You can use:

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

I've moved - to the end of the character class so that it is treated literally and not as range operator. The same problem exists in your original regex too where - is being treated as range operator.

Also I've dropped redundant ' and " from the char class.

Upvotes: 5

T.J. Crowder
T.J. Crowder

Reputation: 1074505

The expression is probably wrong to start with. You have /^([a-zA-Z0-9_ -.''""]+)$/ where you probably mean /^([a-zA-Z0-9_ \-.''""]+)$/ (note the backslash in front of the dash). The - within [] indicates a range, so -. (space dash dot) means "from a space through to a dot" and if you put the colon in there, it just changes that range.

So adding the colon and escaping the dash (and removing the redundant ' and " near the end), you probably want: /^([a-zA-Z0-9_ \-.'":]+)$/

Upvotes: 1

Related Questions