从String获取特定文本

时间:2014-11-06 12:27:59

标签: java android string split substring

我有一个类似的字符串..

String desc = "<a href='http://indiatoday.intoday.in/story/nda-black-money-narendra-modi-fema-supreme-court/1/398323.html'><img src='http://media2.intoday.in/indiatoday/images/stories/black-money-nov10-2_167_103114093357.jpg'"

我想从这个字符串中获取href和src的数据..比如

String link1 = "http://indiatoday.intoday.in/story/nda-black-money-narendra-modi-fema-supreme-court/1/398323.html";
String link2 = "http://media2.intoday.in/indiatoday/images/stories/black-money-nov10-2_167_103114093357.jpg";

有什么方法可以做到这一点。请帮忙。

3 个答案:

答案 0 :(得分:1)

考虑使用以下RegExp:(href | src)='" ['"]

Pattern p = Pattern.compile("(href|src)=['\"]([^'\"]['\"]+)");
Matcher m = p.matcher(desc);

if (m.matches) {
   // grab all the groups and use what you need.
}

进一步阅读:http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

答案 1 :(得分:0)

尝试从索引获取链接:

String link1 = desc.substring(desc.indexOf("href='")+6,desc.indexOf(".html")+5);
String link2 = desc.substring(desc.indexOf("src='")+5,desc.lastIndexOf("'"));

我知道这不是一般化的解决方案,但它会挑战解决给定的要求。

答案 2 :(得分:0)

你可以像这样使用子串

String desc = "<a href='http://indiatoday.intoday.in/story/nda-black-money-narendra-modi-fema-supreme-court/1/398323.html'><img src='http://media2.intoday.in/indiatoday/images/stories/black-money-nov10-2_167_103114093357.jpg'";

    String string1 = desc.substring(desc.indexOf("f") + 2,
            desc.indexOf("img"));
    String string2 = desc.substring(desc.indexOf("src") + 2);

或者您也可以使用@Adrian B代码