2011-02-27 92 views
0

我正在嘗試在大文本中查找特定短語,但該短語可能包含「[」,「(」,「*」等字符,...如「name1(name2」,但它會導致無效。例外尋找它的時候,這裏是我的代碼:如何將模式與內部的括號相匹配?

Pattern myPattern = Pattern.compile("\\b" + phrase + "\\b"); // Exception 
Matcher myMatcher = myPattern.matcher(largeText); 

我曾嘗試使用引號(...),以解決此類字符,但它沒有工作:

phrase = Pattern.quote(phrase); 

哪有我解決這個問題以允許這樣的字符?

+0

我認爲這是因爲這些是字邊界字符,所以他們被'\ b'抓住,切斷你的匹配? – BoltClock 2011-02-27 09:51:54

+0

您能否詳細說明爲什麼Pattern.quote不起作用?這似乎是在這裏使用的優雅解決方案。 – mmccomb 2011-02-27 09:52:25

+0

@BoltClock,像'\ b'這樣的錨符合空字符串,它們只用於限制特定位置的模式匹配,但它們不會「消耗」任何東西。 – 2011-02-27 10:00:48

回答

2

Pattern.quote(phrase)作品就好了:

String largeText = "a()b a()c a()b"; 
String phrase = "a()b"; 
Pattern myPattern = Pattern.compile("\\b" + Pattern.quote(phrase) + "\\b"); 
Matcher myMatcher = myPattern.matcher(largeText); 
while(myMatcher.find()) { 
    System.out.println(myMatcher.group()); 
} 

打印:

a()b 
a()b 
+0

..你是對的巴特。使用引號(...)後,我得到了同樣的異常,所以我認爲這並沒有解決它。但在追蹤我的代碼後,我發現它發生在另一行後...感謝每個人的答案。 – Brad 2011-02-27 13:29:24

+0

@布拉德,不客氣。很高興聽到你追蹤了這個錯誤。 – 2011-02-27 13:31:37

0

過程短語來轉義所有可能的正則表達式元字符。

0

能否請您提供重現這個問題的完整的例子嗎?我試過以下,它工作正常:

String largeText = "large text with name1 (name2) and possibly something more"; 
String phrase = "name1 (name2"; 
phrase = Pattern.quote(phrase); 
Pattern myPattern = Pattern.compile("\\b" + phrase + "\\b"); // Exception 
System.out.println("The pattern is " + myPattern.pattern()); 
Matcher myMatcher = myPattern.matcher(largeText); 
if (myMatcher.find()) { 
    System.out.println("A match is found: " + myMatcher.group()); 
} 

輸出是:

The pattern is \b\Qname1 (name2\E\b 
A match is found: name1 (name2 
0

您可能希望只使用:

int offset = largeText.indexOf(phrase); 

測試存在/偏移一個子串。

使用模式,這應該工作:

String longString = "this[that]the other* things"; 
String phrase = "[that]"; 
Pattern myPattern = Pattern.compile("\\b" + Pattern.quote(phrase) + "\\b")); 
Matcher m = myPattern.matcher(longString); 
if (m.find()) { 
    System.out.println(m.group()); 
} 

但在使用時,有一個小問題*和?在短語的開頭或結尾。

這些字符被視爲空白字符(而不是單詞字符),因此如果它們出現在短語的開頭或結尾,則匹配邊界時必須包含所有前導/尾隨空格。

如果短語在開頭或結尾處包含這些字符,則可能需要刪除「\ b」來解決此問題。

相關問題