开发者

Retrieve certain text in a bigger text

I want to retrieve a text starting with "ht开发者_如何转开发tp" and finishing with ".jpg" in a content i have . What i did for now is :

public void captureURL(String content){
    for(int i = 0; i < content.length() ; i++){
        String test = content.substring(i);
        if(test.startsWith("http://") && test.endsWith(".jpg")){

        }
    }
}

The big picture is : i take the content of a page with Asynctask, and search for the image URL . And save it in some variables.


You can use regexes here:

Pattern p = Pattern.compile("http\\://.+?\\.jpg");
Matcher m = p.matcher(content);
while (m.find())
{
     System.out.println(content.substring(m.start(), m.end()));
}


Try this:

    String html = "http://image1.jpg sometext http://image2.jpg";
    Pattern p = Pattern.compile("http.*?jpg");
    Matcher m = p.matcher(html);
    while (m.find())
        System.out.println(m.group());


No need to search by substring..

public void captureURL(String content){

        if(content.startsWith("http://") && content.endsWith(".jpg")){

        }
}


This is how I would think if doing it without using any utility functions. it takes O(n) runtime since it only loops once:

public static ArrayList<String> captureURL(String content) {
    ArrayList<String> urls = new ArrayList<String>();
    boolean currentlyInURL = false;
    String url = "";
    for (int i = 0; i + 4 <= content.length(); i++) {
      if (content.substring(i, i + 4).equals("http")) {
        url += content.substring(i, i + 1);
        currentlyInURL = true;
      } else if (content.substring(i, i + 4).equals(".jpg") && currentlyInURL) {
        url += content.substring(i, i + 4);
        urls.add(url);
        url = "";
        currentlyInURL = false;
      } else if (currentlyInURL && i != content.length() - 1) {
        url += content.substring(i, i + 1);
      }
    }
    return urls;
  }

and the following test:

  public static void main(String[] args) {
    String content = "blah blah http://dfdfsdf.jpgcool cool http://ssfk.jpgddddd";
    for (String url : captureURL(content)) {
      System.out.println(url);
    }
  }

prints the following in the console:

http://dfdfsdf.jpg
http://ssfk.jpg
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜