4

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!

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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 \-']+$ 

Comments

0

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.

Comments

-4
regExp = /^[0-9A-Za-z\$ ]{0,30}$/; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.