Regex pattern including all special characters

后端 未结 18 1541
爱一瞬间的悲伤
爱一瞬间的悲伤 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:43

    Use this regular expression pattern ("^[a-zA-Z0-9]*$") .It validates alphanumeric string excluding the special characters

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

    For people (like me) looking for an answer for special characters like Ä etc. just use this pattern:

    • Only text (or a space): "[A-Za-zÀ-ȕ ]"

    • Text and numbers: "[A-Za-zÀ-ȕ0-9 ]"

    • Text, numbers and some special chars: "[A-Za-zÀ-ȕ0-9(),-_., ]"

    Regex just starts at the ascii index and checks if a character of the string is in within both indexes [startindex-endindex].

    So you can add any range.

    Eventually you can play around with a handy tool: https://regexr.com/

    Good luck;)

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

    We can achieve this using Pattern and Matcher as follows:

    Pattern pattern = Pattern.compile("[^A-Za-z0-9 ]");
    Matcher matcher = pattern.matcher(trString);
    boolean hasSpecialChars = matcher.find();
    
    0 讨论(0)
  • 2020-12-02 09:45

    Please use this.. it is simplest.

    \p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~

    https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

        StringBuilder builder = new StringBuilder(checkstring);
        String regex = "\\p{Punct}"; //Special character : `~!@#$%^&*()-_+=\|}{]["';:/?.,><
        //change your all special characters to "" 
        Pattern  pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(builder.toString());
        checkstring=matcher.replaceAll("");
    
    0 讨论(0)
  • 2020-12-02 09:46

    To find any number of special characters use the following regex pattern: ([^(A-Za-z0-9 )]{1,})

    [^(A-Za-z0-9 )] this means any character except the alphabets, numbers, and space. {1,0} this means one or more characters of the previous block.

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

    (^\W$)

    ^ - start of the string, \W - match any non-word character [^a-zA-Z0-9_], $ - end of the string

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