0

<img src='http://res.cloudinary.com/test/image/upload/v1/testFolder/1024x1024.jpg'/>

I want to get the url which is between ' and '. This is what I tried and it gives String index out of range : -1 error.

String html = "<img src='http://res.cloudinary.com/test/image/upload/v1/testFolder/1024x1024.jpg'/>";

html.substring((html.indexOf("'")), html.indexOf("'"));

and also I tried html.substring((html.indexOf("'")) +1 , html.indexOf("'"));

How can I get the url between ' and '?

happyman
  • 33
  • 1
  • 1
  • 4

3 Answers3

3

You need to retain the first index so that you can search for the next one beyond that point

int idx = html.indexOf("'") + 1;
int idx2 = html.indexOf("'", idx); // this will find the next ' character

System.out.println(html.substring(idx, idx2));
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

You have to change html.indexOf("'") to html.lastIndexOf("'").

try it:

public static void main(String[] args) throws ClassNotFoundException {
    String html = "<img src='http://res.cloudinary.com/test/image/upload/v1/testFolder/1024x1024.jpg'/>";

    System.out.println(html.substring(html.indexOf("'") + 1, html.lastIndexOf("'")));
}
Roma Khomyshyn
  • 1,112
  • 6
  • 9
0

You could also use a regex pattern....

Pattern p = Pattern.compile("'(.*?)'");
Matcher m = p.matcher(html);
m.find();
m.group(1); // will return http://res.cloudinary.com/test/image/upload/v1/testFolder/1024x1024.jpg
Ben Arnao
  • 153
  • 4
  • 14