Want to search in String if there is any special characters in it

前端 未结 3 1600
萌比男神i
萌比男神i 2021-01-28 19:27

I want to search any special char in java string. here is my code

    Pattern p = Pattern.compile(\"^[a-zA-Z0-9 ]\");
    Matcher m = p.matcher(\"hgbs!hf862376\"         


        
相关标签:
3条回答
  • 2021-01-28 19:58

    From the JavaDocs:

    • Matcher.matches() attempts to match the entire input sequence against the pattern.
    • Matcher.find() scans the input sequence looking for the next subsequence that matches the pattern.

    You should use Matcher.find() is you're looking for some substring (even one character) which matches certain rules like not being alphanumerical.

    Or you could use Matcher.matches(), but then the regular expression pattern should be [a-zA-Z0-9 ]+, meaning you want a match if the string consists only of valid characters. If any other character appears then matches() will return false.

    0 讨论(0)
  • 2021-01-28 20:06

    .*[^a-zA-Z0-9 ].* instead of ^[a-zA-Z0-9 ]

    ^ within character class (i.e. square brackets) mean negation, so any but the characters listed. If not within character class, ^ means the beggining of the string. Also you need to match anything before or after the special character. So your original regex would have matched only strings that have a single letter among a-zA-Z0-9.

    0 讨论(0)
  • 2021-01-28 20:10
    Pattern p = Pattern.compile("^[a-zA-Z0-9]*$");
    Matcher m = p.matcher("hgbs!hf862376");
    boolean b = m.matches(); // looking for no special characters
    
    if (!b) {
        System.out.println("sp. character is there");
    }
    
    0 讨论(0)
提交回复
热议问题