Regular expression include and exclude special characters

前端 未结 3 398
故里飘歌
故里飘歌 2020-12-30 01:22

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

Allowed Characters

Alphabet : a-z / A-Z
Numbers : 0-9
Special Characters : ~ @ # $ ^ &

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-30 01:50

    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.

提交回复
热议问题