0

我有这个字符串

<div><img width="100px" src="http://www.mysite.com/Content/dataImages/news/small/some-pic.png" /><br />This is some text that I need to get.</div>

我需要This is some text that I need to get.从上面的Java字符串中获取图像链接和文本。谁能告诉我我该怎么做?

4

4 回答 4

1

使用正则表达式得到你想要的。

于 2013-03-01T06:39:11.880 回答
1

我的解决方案是:

String tmp=xpp.nextText();
desc=android.text.Html.fromHtml(tmp).toString();
img=FindUrls.extractUrls(tmp);

从我使用的字符串中提取文本:

desc=android.text.Html.fromHtml(tmp).toString();
img=FindUrls.extractUrls(tmp);

对于字符串中的链接,我使用了这个函数:

 public static String extractUrls(String input) {

        String result = null;
        Pattern pattern = Pattern.compile(
            "\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)" + 
            "(\\w+:\\w+@)?(([-\\w]+\\.)+(com|org|net|gov" + 
            "|mil|biz|info|mobi|name|aero|jobs|museum" + 
            "|travel|[a-z]{2}))(:[\\d]{1,5})?" + 
            "(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" + 
            "((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + 
            "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" + 
            "(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + 
            "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" + 
            "(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b");

        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            result=matcher.group();
        }
        return result;
    }

希望它会帮助有类似问题的人

于 2013-03-01T08:56:58.033 回答
1

如果这就是你所要做的,那么引入额外的包是没有意义的,只需使用正则表达式:模式 "(?<=src=\")(.*?)(?=\")" 可用于获取链接,您可以修改它以提供文本。

于 2013-03-01T07:09:31.507 回答
1

试试这个,如果你必须改变模式。

String str = "<div><img width=\"100px\" src=\"http://www.mysite.com/Content/dataImages/news/small/some-pic.png\" /><br />This is some text that I need to get.</div>";
Pattern p = Pattern.compile("src=\"(.*?)\" /><br />(.*?)</div>");
Matcher m = p.matcher(str);
if (m.find()) {
    String link = m.group(1);
    String text = m.group(2);
}
于 2013-03-01T07:58:07.380 回答