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\"
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.
.*[^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
.
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");
}