views:

66

answers:

1

Hi,

I have a regular expression that searches for the special characters.

When I do a search on numerics, e.g. 3, I always get 0, when I'd expect to get -1.

'3'.search(/[!\"£\$%\^&\*\(\)-_\+=\[\]\{\};:@\'#\\|<,\.>\/\?]/)

Any idea why is this happening?

+5  A: 
\)-_

This causes the character class to include all characters between ) and _, i.e. )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_. 3 is in one of these.

The - should be placed at the beginning or end, so that it won't be counted as a special character. Also, besides \, [, ] and /, there's no need to escape anything in a character class.

/[-!"£$%^&*()_+=\[\]{};:@'#\\|<,.>\/?]/

(Technically the [ doesn't need to be escaped either, but for consistency I prefer to escape it. Also, you could match a - in the middle if you escape it \-.)

KennyTM
Star, thank you very much! Can accept in 10 min.. :)
vikp