Regex pattern including all special characters

后端 未结 18 1540
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 09:18

I want to write a simple regular expression to check if in given string exist any special character. My regex works but I don\'t know why it also includes all numbers, so wh

相关标签:
18条回答
  • 2020-12-02 09:35

    I have defined one pattern to look for any of the ASCII Special Characters ranging between 032 to 126 except the alpha-numeric. You may use something like the one below:

    To find any Special Character:

    [ -\/:-@\[-\`{-~]
    

    To find minimum of 1 and maximum of any count:

    (?=.*[ -\/:-@\[-\`{-~]{1,})
    

    These patterns have Special Characters ranging between 032 to 047, 058 to 064, 091 to 096, and 123 to 126.

    0 讨论(0)
  • 2020-12-02 09:35

    Try using this for the same things - StringUtils.isAlphanumeric(value)

    0 讨论(0)
  • 2020-12-02 09:38

    That's because your pattern contains a .-^ which is all characters between and including . and ^, which included digits and several other characters as shown below:

    enter image description here

    If by special characters, you mean punctuation and symbols use:

    [\p{P}\p{S}]
    

    which contains all unicode punctuation and symbols.

    0 讨论(0)
  • 2020-12-02 09:40

    If you only rely on ASCII characters, you can rely on using the hex ranges on the ASCII table. Here is a regex that will grab all special characters in the range of 33-47, 58-64, 91-96, 123-126

    [\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]
    

    However you can think of special characters as not normal characters. If we take that approach, you can simply do this

    ^[A-Za-z0-9\s]+
    

    Hower this will not catch _ ^ and probably others.

    0 讨论(0)
  • 2020-12-02 09:41

    SInce you don't have white-space and underscore in your character class I think following regex will be better for you:

    Pattern regex = Pattern.compile("[^\w\s]");
    

    Which means match everything other than [A-Za-z0-9\s_]

    Unicode version:

    Pattern regex = Pattern.compile("[^\p{L}\d\s_]");
    
    0 讨论(0)
  • 2020-12-02 09:43

    Here is my regex variant of a special character:

    String regExp = "^[^<>{}\"/|;:.,~!?@#$%^=&*\\]\\\\()\\[¿§«»ω⊙¤°℃℉€¥£¢¡®©0-9_+]*$";
    

    (Java code)

    0 讨论(0)
提交回复
热议问题