html标记中的文本,提供带有属性的标记名称

时间:2017-10-21 12:39:20

标签: java regex

我有一个字符串看起来像这样 -

  <h3 class="media__title"> 
  <a class="media__link" href="/news/world-europe41644527" rev="video|headline">
  The equestrian champion with no legs                                                         
  </a> </h3>

我尝试阅读并使用此内容获取h3标签内的文本 模式

 String regex = <h3>(.+?)</h3>

我使用的代码

 private ArrayList<String> getValues(String resource) {
    final ArrayList<String> values= new ArrayList<>();
    final Matcher matcher = regex.matcher(str);
    while (matcher.find()) {
        values.add(matcher.group(1));
    }
    return values;
}

如果我从h3标签中删除class=media__title属性,此代码将起作用。我尝试将正则表达式更改为此

String regex = <h3 class=\"medial__title\">(.+?)</h3>

仍然没有进展。有人能告诉我这个正则表达式模式应该改变什么吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

String regex = <h3 (.*)>((.|\s)+?)<\/h3>

你的方法的主要问题是。字符与行终止符不匹配。

说明:

<h3 (.*)> matches an opening h3 tag together with all attributes contained (you could also use different patterns if you are interested in the attributes themselfs)

((.|\s)+?) match everything inside the h3 tag (.|s) means everything ("everything but line terminators or whitesaces")

<\/h3> the closing h3 tag (escaped because / is a regex delimiter)

请记住,现在您正在寻找的群组是第二组,而不是第一组

相关问题