Java Regex从HTML锚点(< a> ...< / a>)标签中获取文本 [英] Java Regex to get the text from HTML anchor (<a>...</a>) tags

查看:103
本文介绍了Java Regex从HTML锚点(< a> ...< / a>)标签中获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get a text within a certain tag. So if I have:

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

我希望能够检索 Found 文字。

I want to be able to retrieve the Found text.

我正在尝试使用正则表达式。如果< a href =http://something.com> 保持不变但我没有这样做,我就能做到。

I'm trying to do it using regex. I am able to do it if the <a href="http://something.com> stays the same but it doesn't.

到目前为止我有这个:

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

我认为最后两部分 - ([a-zA-Z0-9] *)< / a>。* - 没关系,但我不知道该怎么办第一部分。

I think the last two parts - the ([a-zA-Z0-9 ]*)</a>.* - are ok but I don't know what to do for the first part.

推荐答案

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

As they said, don't use regex to parse HTML. If you are aware of the shortcomings, you might get away with it, though. Try

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

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

will iterate over all matches in a string.

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

It won't handle nested <a> tags and ignores all the attributes inside the tag.

这篇关于Java Regex从HTML锚点(&lt; a&gt; ...&lt; / a&gt;)标签中获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆