mr jorden mr jorden - 1 month ago 14
Java Question

Pattern and Matcher is not working in java

Basically I have a simple String Where I need to explicitly restrict characters other than

a-zA-Z0-9
. Before I mention what is wrong here is how I am doing it.

Pattern p = Pattern.compile("[&=]");
Matcher m = p.matcher("Nothing is wrong");
if (m.find()){
out.print("You are not allowed to have &=.");
return;
}

Pattern p1 = Pattern.compile("[a-zA-Z0-9]");
Matcher m1 = p1.matcher("Itissupposetobeworking");
if (m1.find()){
out.print("There is something wrong.");
return;
}


The first one works fine, But on the second matcher
m1
always gets to execute
if(m1.find())
even though it doesn't contain any character other than specified in the pattern.

I also tried
Pattern p1 = Pattern.compile("[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]")
But still have the same trouble.

and if you might wanna tell, which is better between
String.matches(["a-zA-Z0-9"]);
or the way I am using above?

Thanks in advance.

Answer

You seem to want to find a partial match in a string that contains a character other than an alphanumeric character:

Pattern p1 = Pattern.compile("[^a-zA-Z0-9]");

or

Pattern p1 = Pattern.compile("\\P{Alnum}");

The [^a-zA-Z0-9] pattern is a negated character class that matches any char other than the ones defined in the class. So, if a string contains any chars other than ASCII letters or digits, your if (m1.find()) will get triggered and the message will appear.

Note that the whole negated character class can be replaced with a predefined character class \P{Alnum} that matches any char other than alphanumeric. \p{Alnum} matches any alphanumeric character and \P{Alnum} is the reverse class.