2015-03-19 79 views
0

我正在嘗試編寫一個方法,該方法檢查文本文件中特定字是否被特定字符集封裝。舉例來說,如果我的關鍵詞是「blablabla」,和字符集是HTML標題標籤, (例如Java方法檢查關鍵字包圍的HTML標題標記

<h2> blabla </h2> 

),該方法應該返回true。然而,關鍵字本身可以通過不同的關鍵字包圍(例如

<h2> something something blabla in the month of may </h2> 

)在這種情況下該方法仍具有返回true,由於關鍵詞仍然由定義字符集包圍。 這裏是我的媒體鏈接有:

public static Boolean KeywordIsInTitle(String text, String keywordInText){ 
     boolean isInTitle = false; 
     if(text.contains(keywordInText) == true){ 
      /*Here is wehre I am stuck.... 
      * */ 

      isInTitle = true;} 
     return isInTitle; 
    } 

我一直在尋找的正則表達式和一個小時左右,模式匹配,但沒有工作,我不得不承認,我不FFEL很舒服,很熟悉論文概念尚未... 任何人都可以幫忙嗎?非常感謝你提前!

+0

此方法只返回true。然而在if檢查中不需要==真。 – Rajesh 2015-03-19 12:56:17

+0

你想用正則表達式嗎?否則你可以簡單地寫'return text.contains(keywordInText);' – Prashant 2015-03-19 12:56:35

+0

@Prashant好吧,這就是要點;如上所述,檢查關鍵字是否在文本中不是問題。問題是檢查它是否被html標籤包圍! – 2015-03-19 13:02:07

回答

1
import java.util.regex.Pattern; 

public class Match { 
    public static void main(String[] args) { 
     String s1 = "<h2> blabla </h2>"; 
     String s2 = " <h2> some other string </h2>"; 
     final String regex = "<h2>(.)*blabla(.)*<\\/h2>"; 

     boolean b1 = Pattern.matches(regex, s1); 
     boolean b2 = Pattern.matches(regex, s2); 

     System.out.printf("the value of b1 is %b\n", b1); 
     System.out.printf("the value of b2 is %b\n", b2); 
    } 
} 
0

嘗試正則表達式

(<h1>.+<\/h2>) // Matches <h1>StackOverflow</h2> 

Demo