2016-09-16 87 views
1
  1. 我已經在此共享我的示例代碼。在這裏我試圖找到帶有不同字符串的字「引擎」。我用字邊界來匹配字符串中的單詞。
  2. 它匹配單詞,如果它以#engine開頭(示例)。
  3. 它應該只匹配確切的單詞。如何在java中使用模式匹配器找到匹配的確切單詞

    private void checkMatch() { 
        String source1 = "search engines has "; 
        String source2 = "search engine exact word"; 
        String source3 = "enginecheck"; 
        String source4 = "has hashtag #engine"; 
        String key = "engine"; 
    
        System.out.println(isContain(source1, key)); 
        System.out.println(isContain(source2, key)); 
        System.out.println(isContain(source3, key)); 
        System.out.println(isContain(source4, key)); 
    
    } 
    
    private boolean isContain(String source, String subItem) { 
        String pattern = "\\b" + subItem + "\\b"; 
        Pattern p = Pattern.compile(pattern); 
        Matcher m = p.matcher(source); 
        return m.find(); 
    } 
    
    **Expected output** 
        false 
        true 
        false 
        false 
    
    **actual output** 
        false 
        true 
        false 
        true 
    
+0

如果字符串包含整個單詞'engine',您只需要得到真或假?而且:你只是在尋找文字文字嗎? –

+0

對於確切的字符串,正則表達式搜索並不是真正的高性能。只要刪除'\ b's(java.util.Matcher將切換到字符串搜索),並檢查邊界是否爲空白。 – CoronA

回答

1

對於這種情況,你必須使用正則表達式,而不是單詞邊界OR。 \\b匹配單詞char和非單詞char(反之亦然)。因此,您的正則表達式應在#engine中找到匹配項,因爲#是非單詞字符。

private boolean isContain(String source, String subItem) { 
    String pattern = "(?m)(^|\\s)" + subItem + "(\\s|$)"; 
    Pattern p = Pattern.compile(pattern); 
    Matcher m = p.matcher(source); 
    return m.find(); 
} 

String pattern = "(?<!\\S)" + subItem + "(?!\\S)"; 
+0

其返回true爲所有的情況@Avinash –

+0

看到這個演示https://regex101.com/r/yA3pD8/1 –

+0

和https://regex101.com/r/yA3pD8/2 –

0

如下改變你的模式。

String pattern = "\\s" + subItem + "\\b"; 
0

如果您正在尋找封閉用空格或開始/結束的字符串字面文字,你可以用一個單純的空白格式,如:\s+分割字符串,並檢查是否有任何塊等於搜索文本。

Java demo

String s = "Can't start the #engine here, but this engine works"; 
String searchText = "engine"; 
boolean found = Arrays.stream(s.split("\\s+")) 
     .anyMatch(word -> word.equals(searchText)); 
System.out.println(found); // => true 
0
更改

正則表達式到

String pattern = "\\s"+subItem + "\\s"; 

我使用

\ S空白字符:[\噸\ n \ X0B \˚F \ r]

欲瞭解更多信息窺視java.util.regex.Pattern的javadoc

此外,如果你想支持串這樣的:通過將結束/開始行終止

"has hashtag engine" 
"engine" 

可以提高它(^和$) 使用此模式:

String pattern = "(^|\\s)"+subItem + "(\\s|$)";