在java中,我試圖確定用戶輸入的字符串(意思是我不知道輸入是什麼)恰好被包含在另一個字符串中,在字邊界上。因此the
的輸入在文本there is no match
中不應匹配。如果輸入字符串中有標點符號,我會遇到問題,並可以使用一些幫助。Java正則表達式與問號和字邊界完全匹配
在沒有標點符號的,這工作得很好:
String input = "string contain";
Pattern p = Pattern.compile("\\b" + Pattern.quote(input) + "\\b");
//both should and do match
System.out.println(p.matcher("does this string contain the input").find());
System.out.println(p.matcher("does this string contain? the input").find());
然而,當輸入中有一個問號,用字邊界匹配似乎不工作:
String input = "string contain?";
Pattern p = Pattern.compile("\\b" + Pattern.quote(input) + "\\b");
//should not match - doesn't
System.out.println(p.matcher("does this string contain the input").find());
//expected match - doesn't
System.out.println(p.matcher("does this string contain? the input").find());
//should not match - doesn't
System.out.println(p.matcher("does this string contain?fail the input").find());
任何幫助,將不勝感激。
@quackenator通過添加'Pattern.quote()',您不必轉義任何特殊字符 – diginoise
應該'失敗!'與'fail!'匹配(爲避免混淆,留下一個問號) – steffen
好問題@steffen - 是的 - 想要將任何標點符號不直接作爲「字邊界」的一部分輸入 –