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

前端 未结 3 1640
萌比男神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.

提交回复
热议问题