Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression include and exclude special characters

Tags:

I'm finding a regular expression which adheres below rules.

Allowed Characters

Alphabet : a-z / A-Z
Numbers : 0-9
Special Characters : ~ @ # $ ^ & * ( ) - _ + = [ ] { } | \ , . ? :
(spaces should be allowed)

Not Allowed

Special Characters : < > ' " / ; ` %

like image 766
Janith Avatar asked Apr 16 '12 11:04

Janith


People also ask

How do you restrict special characters in regex?

var nospecial=/^[^* | \ " : < > [ ] { } ` \ ( ) '' ; @ & $]+$/; if(address. match(nospecial)){ alert('Special characters like * | \ " : < > [ ] { } ` \ ( ) \'\' ; @ & $ are not allowed'); return false; but it is not working.

What is ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.

What is difference [] and () in regex?

This answer is not useful. Show activity on this post. [] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.


1 Answers

For the allowed characters you can use

^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$ 

to validate a complete string that should consist of only allowed characters. Note that - is at the end (because otherwise it'd be a range) and a few characters are escaped.

For the invalid characters you can use

[<>'"/;`%] 

to check for them.

To combine both into a single regex you can use

^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%]) 

but you'd need a regex engine that allows lookahead.

like image 153
Joey Avatar answered Oct 06 '22 14:10

Joey