Rakim
Rakim

Reputation: 1107

if statement and regular expressions java

I am trying to implement an if statement to accept any word consisting with any of the letters a-k (both upper and lower case) in Java. My input is a String. I guess it would be something like:

if(input.equals("[a-kA-K]+")){
    System.out.println("the input was: $0");
}

but I am not sure how to do it.

Upvotes: 1

Views: 14439

Answers (2)

kosa
kosa

Reputation: 66637

I think you need to do something like pattern match. Example:

Pattern p = Pattern.compile("a*b");
 Matcher m = p.matcher("aaaaab");
 boolean b = m.matches();

Then

if(b)
{
 //Your code.
}

From @yshavit comments (which are important):

Worth noting that the Pattern p object is immutable and thread-safe, and can be shared (e.g. by creating the Pattern once and storing it in a private static final). If you don't care about creating the Pattern each time, and you don't need access to captured groups in the regex, you can also just call the static Pattern.matches(pattern, stringToLookIn)

Upvotes: 3

proowl
proowl

Reputation: 101

If input is String, then you can use input.matches("[a-kA-K]+").

Documentation: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches(java.lang.String)

Upvotes: 2

Related Questions