繁体   English   中英

如何从字符串<a>标签中</a>提取网址和标签<a>?</a>

[英]How to extract url and label from String <a> tag?

我有一个字符串格式为<a href="http://example.com">Example</a><a>标签列表。 从此字符串中提取URL http://example.com和标签Example的最佳方法是什么。 当前,我使用子字符串方法来标识边界并获取url和标签。 但是,使用正则表达式还有更好的方法吗?

您想要查看JSoup来从html中提取值。

它们提供几乎正是你想要的例子在这里

Document doc = Jsoup.connect("http://jsoup.org").get();

Element link = doc.select("a").first();
String relHref = link.attr("href"); // == "/"
String absHref = link.attr("abs:href"); // "http://jsoup.org/"

也许您会选择一个好的HTML解析器。 即JSoup。

String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";
Document doc = Jsoup.parse(html);
Element link = doc.select("a").first();

String text = doc.body().text(); // "An example link"
String linkHref = link.attr("href"); // "http://example.com/"
String linkText = link.text(); // "example""

String linkOuterH = link.outerHtml(); 
    // "<a href="http://example.com"><b>example</b></a>"
String linkInnerH = link.html(); // "<b>example</b>"

这是正则表达式:

“ \\\\”(。*?)\\“ \\”

尽管我建议您使用特定于HTML属性提取的工具。

您可以使用Apache commons substringBetween方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM