startsWith endsWith匹配包含正则表达式

bra*_*all 2 java regex android

如果用户回答"是"或"否",我将遍历语音数据的数组列表来解密.简单嘿......

这是我必须检测到包含"是"和"否"的不明确响应的初始检查.它工作得很好,但只是看着它,我知道我应该尴尬发布它,它可以大大简化!

    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
Run Code Online (Sandbox Code Playgroud)

我希望用户能够接受或拒绝使用他们想要的任何自然语音,因此需要考虑数组数据中出现以下不可能的事件:

  • 是的
  • sey on
  • 是的敲门
  • 昨天没有
  • 昨天敲门
  • 贝叶斯定理色情

我经历了很多正则表达式帖子和教程,但无论我做什么,我都找不到比发布的代码更好的解决方案.白色空间[\\ s]在那里或'|' 不,我无法解决......

我提前感谢你的帮助!

IBB*_*ard 6

如果你只想要单词"yes"或"no"(即"bayes theorem porno"和"昨天" 匹配)那么你可以\b在正则表达式中用作边界字符:PatternJavaDoc,Boundaries tutorial

假设你已经低估了输入,那么这应该有效:

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
}
Run Code Online (Sandbox Code Playgroud)

测试代码:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `\ b`表示"单词边界",基本上匹配下一个字符是任何不是单词字符(`\ w`)的点,包括行的开头和结尾,所以"no","fred no"鲍勃"和"fred-no-bob"应该匹配,但不是"fred non bob".尝试在http://www.regextester.com/这样的地方(但没有转义斜线 - 所以在很多正则表达式测试网站上只有`\ bno\b`) (2认同)