Reputation: 6144
I'm iterating through an array list of voice data to decipher if the user answered 'yes' or 'no'. Simple hey...
This is the initial check I have to detect an unclear response that contains both 'yes' and 'no'. It works perfectly, but just looking at it, I know I should be embarrassed to post it and it can be greatly simplified!
if ((element.toString().startsWith("yes ")
|| element.toString().endsWith(" yes")
|| element.toString().contains(" yes "))
&& (element.toString().startsWith("no ")
|| element.toString().endsWith(" no")
|| element.toString().contains(" no "))) {
// I heard both yes and no - inform user I don't understand
I want the user to be able to accept or decline using whatever natural speech they desire and therefore need to consider the unlikely eventualities of the following appearing in the array data:
I've been through so many regular expression posts and tutorials, but no matter what I do, I cannot find a solution that works better than the posted code. The white space [\\s] being there or '|' not, I can't resolve...
I thank you in advance for your help!
Upvotes: 2
Views: 4557
Reputation: 969
If you want just the word "yes" or "no" (i.e. "bayes theorem porno" and the "yesterday" ones don't match) then you can use \b
as a boundary character in a regex: Pattern
JavaDoc, Boundaries tutorial
Assuming you're already lower-casing the input then this should work:
Pattern yes = Pattern.compile(".*\\byes\\b.*");
Pattern no = Pattern.compile(".*\\bno\\b.*");
...
bool matchesYes = yes.matcher(input).matches();
bool matchesNo = no.matcher(input).matches();
if (matchesYes == matchesNo) {
... //Do "invalid answer" here -
//we either matched both (true, true) or neither (false, false)
} else if (matchesYes) {
... //Do "Yes" here
} else { //Else matches No
... //Do "No" here
}
Test code:
private static Pattern yes = Pattern.compile(".*\\byes\\b.*");
private static Pattern no = Pattern.compile(".*\\bno\\b.*");
/**
* @param args
*/
public static void main(String[] args) {
TestMethod("yes"); //Yes
TestMethod("no"); //No
TestMethod("yesterday"); //Bad
TestMethod("fred-no-bob"); //No
TestMethod("fred'no'bob"); //No
TestMethod("fred no bob"); //No
TestMethod("snow"); //Bad
TestMethod("I said yes"); //Yes
TestMethod("yes no"); //Bad
TestMethod("no yes"); //Bad
}
private static void TestMethod(String input) {
System.out.print("Testing '" + input + "': ");
bool matchesYes = yes.matcher(input).matches();
bool matchesNo = no.matcher(input).matches();
if (matchesYes == matchesNo) {
System.out.println("Bad");
} else if (matchesYes) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
Upvotes: 6