Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to validate only A-Z, a-z, 0-9, space, period, hyphen - exclamation mark ! question mark ? quotes "

Tags:

regex

I want to use regular expression which validate the text which user enter.

/^[a-zA-Z0-9 ]+$/

By above line, we can allow only Alphabetic, Numbers and Space.

What will be regular expression to allow:

alphabetic,
numbers,
space,
period .
hyphen -
exclamation mark !
question mark ?
quotes "

Except above characters user can not enter other characters.

Thanks, naveenos

like image 989
naveenos Avatar asked Dec 04 '22 07:12

naveenos


2 Answers

You're almost there. Try this:

/^[a-zA-Z0-9 .!?"-]+$/

Note that the position of the - character is important. If it appears between two characters (e.g. a-z) it represents a character range. If it appears in at the beginning or end of the character class (or if it's escaped) it represents a literal hyphen character.

like image 140
p.s.w.g Avatar answered Mar 06 '23 10:03

p.s.w.g


You just need to include this extra symbols in the character class you have in your regex.

You can use this regex:

/^[a-zA-Z0-9 "!?.-]+$/
like image 31
anubhava Avatar answered Mar 06 '23 09:03

anubhava