Moira Moira - 2 months ago 7
Java Question

How do I match the string?

I've written a method for matching string input to a certain pattern before the program moves forward but Netbeans IDE is telling me that the escape characters are illegal. I'm not sure how to fix it.

The method is as follows:

public static boolean patternMatch(String ct){

if(ct.equals("\d\d:\d\dam")){
return true;
}
else {
if(ct.equals("\d\d:\d\dpm"))
return true;
}

return false;
}


The pattern is a time pattern that needs to match ##:##am or ##:##pm based on the input from the user. Is this one going to work? Is there a way I can get it to match the input with the pattern this way?

Answer

First .. don't forget to double escaping because of Java (\\d)!!

Use regex function match() that returns boolean as well. You can use classes Matcher and Pattern from the default library java.util.regex..

Pattern p = Pattern.compile("\\d\\d:\\d\\d[ap]m");
Matcher m = p.matcher(str);
boolean matches = m.matches();

Note that you can easily avoid if-else statement using [ap]m that mathes one of a or p giving success on both am and pm.

Or wrap it to a method:

public static boolean patternMatch(String ct) {
    Pattern p = Pattern.compile("\\d\\d:\\d\\d[ap]m");
    Matcher m = p.matcher(ct);
    return m.matches();
}

However the easiest and direct way is:

return ct.matches("\\d\\d:\\d\\d[ap]m");
Comments