Here is a small working example to solve this problem,
public class MyClass {
public static void main(String args[]) {
String[] tests = {"How AND why", "Try AND succeed AND pass", "Try succeed AND", "Try AND AND succeed AND pass", "how ANDY why"};
for(String s: tests){
System.out.println(isValid(s));
}
}
public static boolean isValid(String str){
String[] splitString = str.split("\\bAND\\b", -1);
if(splitString.length == 1){
return false;
}
for(String s: splitString){
if (s.equals(" ") || s.equals("")){
return false;
}
}
return true;
}
}
I am splitting a string using the regex AND
. If AND comes in the start or end of a string, there will always be an empty string in the output of str.split("AND", -1)
. Also, if an AND
is followed by another, a space will also be there in str.split("AND", -1)
. So I check these two conditions in (s.equals(" ") || s.equals(""))
EDIT:
In order to handle strings like how ANDY why
you can use word boundaries \b
in the regex, which will match the whole word. So a regex like \\bAND\\b
will not match the AND
part in ANDY
. Updated the code above to reflect this.