Java Regex从HTML锚点(<a>...</a>)标记中获取文本

时间:2011-01-07 18:04:00

标签: java regex

我正在尝试在某个标签内获取文字。如果我有:

<a href="http://something.com">Found<a/>

我希望能够检索Found文字。

我正在尝试使用正则表达式。如果<a href="http://something.com>保持不变,我就能做到,但事实并非如此。

到目前为止,我有这个:

Pattern titleFinder = Pattern.compile( ".*[a-zA-Z0-9 ]* ([a-zA-Z0-9 ]*)</a>.*" );

我认为最后两部分 - ([a-zA-Z0-9 ]*)</a>.* - 还可以,但我不知道该为第一部分做些什么。

2 个答案:

答案 0 :(得分:6)

正如他们所说,不要使用正则表达式来解析HTML。如果你意识到这些缺点,你可能会侥幸逃脱。尝试

Pattern titleFinder = Pattern.compile("<a[^>]*>(.*?)</a>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher regexMatcher = titleFinder.matcher(subjectString);
while (regexMatcher.find()) {
    // matched text: regexMatcher.group(1)
} 

将迭代字符串中的所有匹配项。

它不会处理嵌套的<a>标记并忽略标记内的所有属性。

答案 1 :(得分:0)

str.replaceAll("</?a>", "");

这是online ideone demo

以下是类似主题:How to remove the tags only from a text ?