views:

409

answers:

3

Hiya,

Can anyone help me with this regex? I need something which will ALLOW:

0-9 a-z A-Z spaces hyphens apostrophes

But disallow all other special characters.

I've got this, but it's not working:

"regex":"/^[0-9a-zA-Z/ /-'_]+$/",

Thanks for any help!

+3  A: 

You should remove the double quotes around the regex:

"regex": /^[0-9a-zA-Z \-'_]+$/,

Also make sure you use backslashes to escape special characters, not forward slashes.

Philippe Leybaert
ah sorry, that was the formatting it had to be in for my javascript. That works fine, thanks!
hfidgen
If you want to allow any white space character, use \s instead of a blank space.
nickyt
A: 

If you want to match underscores as well as alphanumeric charactars (as your code implies), you can use

"regex": /^[\w '-]+$/,

Also, check out this online regular expression testing tool.

scape279
+1  A: 

You could alternatively remove the outer forward slashes and pass it to the constructor of RegExp.

"regex" : new RegExp("^[0-9a-zA-Z \-'_]+$")

Which is equivalent to the /pattern/modifiers syntax (the second argument is an optional string of modifier characters). The \w character class matches alphanumeric characters, including underscore, so I think you can shorten your pattern quite a bit by using it.

^[\w \-']+$
bamccaig