[英]Why doesn't a regex pattern ending in “.” produce a match when using word boundary?
在以下Java代碼中:
public static void main(String[] args) {
String largeText = "abc myphrase. def";
String phrase = "myphrase.";
Pattern myPattern = Pattern.compile("\\b"+Pattern.quote(phrase)+"\\b");
System.out.println("Pattern: "+myPattern);
Matcher myMatcher = myPattern.matcher( largeText );
boolean found = false;
while(myMatcher.find()) {
System.out.println("Found: "+myMatcher.group());
found = true;
}
if(!found){
System.out.println("Not found!");
}
}
我得到這個輸出:
Pattern: \b\Qmyphrase.\E\b
Not found!
請問,有人可以解釋為什么上述模式不會產生匹配嗎? 如果我使用“myphrase”而不是“myphrase”,我確實有匹配。 在模式中。
謝謝您的幫助。
之后沒有邊界.
在單詞字符和非單詞字符之間出現邊界。 既然兩個.
和" "
(空格)是非單詞字符,它們之間沒有邊界。
如果你在你的模式中使用“myphase”,你會得到一個匹配,因為字符e
和the之間有一個邊界.
。
它不匹配,因為點( .
) 不被視為“單詞”字符,因此在文字點之后將沒有單詞邊界(當下一個字符是空格時)。
僅供參考,“單詞”字符(具有自己的正則表達式\\w
)等同於字符類[a-zA-Z0-9_]
也許你正在嘗試使用\\ s而不是\\ b?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.