Regular expression include and exclude special characters

前端 未结 3 397
故里飘歌
故里飘歌 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.

    0 讨论(0)
  • 2020-12-30 02:02
    [a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*
    

    This would do the matching, if you only want to allow that just wrap it in ^$ or any other delimiters that you see appropriate, if you do this no specific disallow logic is needed.

    0 讨论(0)
  • 2020-12-30 02:05

    You haven't actually asked a question, but assuming you have one, this could be your answer...

    Assuming all characters, except the "Special Characters" are allowed you can write

    String regex = "^[^<>'\"/;`%]*$";
    
    0 讨论(0)
提交回复
热议问题