Java 检查关键字是否被 HTML title-tag 包围的方法

Java Method to check if keyword surrounded by HTML title-tag

我目前正在尝试编写一种方法,该方法在文本文件中检查特定单词是否由特定字符集封装。例如,如果我的关键字是 "blablabla",字符集是 html title-tags, (例如

 <h2> blabla </h2>

),该方法应该 return 为真。但是,关键字本身可以被不同的关键字包围(例如

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

) 在这种情况下,该方法仍然必须 return 为真,因为关键字仍然被定义的字符集包围。 这是我已经拥有的:

    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;
    }

我已经研究了正则表达式和模式匹配一​​个小时左右,但没有任何效果,而且我不得不承认我对这些概念还不是很舒服和非常熟悉... 谁能帮忙?非常感谢您!

试试正则表达式

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

Demo

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);
    }
}