mr jorden mr jorden - 1 year ago 69
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

. 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 &=.");

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

The first one works fine, But on the second matcher
always gets to execute
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
or the way I am using above?

Thanks in advance.

Answer Source

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]");


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download