簡體   English   中英

startsWith startsWith匹配包含正則表達式

[英]startsWith endsWith matches contains regular expression

我正在遍歷語音數據的數組列表,以解密用戶是否回答“是”或“否”。 簡單的嘿...

這是我必須檢測到同時包含“是”和“否”的不清楚答案的初始檢查。 它完美地工作,但只是看一下,我知道發布它應該很尷尬,並且可以大大簡化它!

    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

我希望用戶能夠使用他們想要的任何自然語音來接受或拒絕,因此我需要考慮數組數據中出現以下可能性的可能性:

  • 是的沒有
  • sey on
  • 是的,敲
  • 昨天沒有
  • 昨天敲
  • 貝葉斯定理色情

我已經閱讀過許多正則表達式文章和教程,但是無論我做什么,都找不到比發布的代碼更好的解決方案。 空格[\\\\ s]或“ |” 不,我無法解決...

預先感謝您的幫助!

如果只需要單詞“是”或“否”(即“貝葉斯定理色情”而“昨天” 匹配),則可以在正則表達式中使用\\b作為邊界字符: Pattern JavaDocBoundaries 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
}

測試代碼:

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");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM