简体   繁体   中英

if statement and regular expressions java

I am trying to implement an if statement to accept any word consisting with any of the letters ak (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.

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 (eg 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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM