6

我想解析这个链接:

<a href="http://www.google.fr">Link to google</a>

为了得到两个结果:

Link = "http://www.google.fr"
LinkName = "Link to google"

我真的不知道该怎么做,Java中有一个库可以解决这个问题吗?

提前致谢,

4

2 回答 2

2

使用jsoup解析器:

例子:

File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
    String linkHref = link.attr("href");
  String linkText = link.text();
}
于 2012-04-24T15:10:38.033 回答
0

这会做。

public class Parse
{
  public static void main(String[] args)
  {
    String h = " <a href=\"http://www.google.fr\">Link to google</a>";
    int n = getIndexOf(h, '"', 0);

    String[] a = h.substring(n).split(">");
    String url = a[0].replaceAll("\"", "");
    String value = a[1].replaceAll("</a", "");

    System.out.println(url + " - " + value);
  }

  public static int getIndexOf(String str, char c, int n)
  {
    int pos = str.indexOf(c, 0);
    while (n-- > 0 && pos != -1)
    {
      pos = str.indexOf(c, pos + 1);
    }
    return pos;
  }
}
于 2012-04-24T15:29:09.833 回答