wawanopoulos
wawanopoulos

Reputation: 9804

Extract String from another string in Java

Here is a string:

"http://l2.yimg.com/bt/api/res/1.2/iis49xBsStLiYI6LjauR6Q--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/LeMonde.fr/1515504_3_f73c_le-cyber-harcelement-est-une-realite-trop-lo_450282425a88c544c2ff4121a5d9dab4.jpg"

This string is a concatenation of two URLs. I would like to extract only the second URL:

"http://media.zenfs.com/fr_FR/News/LeMonde.fr/1515504_3_f73c_le-cyber-harcelement-est-une-realite-trop-lo_450282425a88c544c2ff4121a5d9dab4.jpg"

How can I do that using Java?

Upvotes: 0

Views: 828

Answers (4)

The Guy with The Hat
The Guy with The Hat

Reputation: 11132

Try using string's .split() method, like this:

String oneURL = twoURLs.split("(?<!^)(?=http://)")[1];

This splits the string in places that are not at the end of the string, but are followed by http://. With that, you should end up with an array like this:

["http://l2.yimg.com/bt/api/res/1.2/iis49xBsStLiYI6LjauR6Q--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/", "http://media.zenfs.com/fr_FR/News/LeMonde.fr/1515504_3_f73c_le-cyber-harcelement-est-une-realite-trop-lo_450282425a88c544c2ff4121a5d9dab4.jpg"]

[1] takes only the second element of that array.

Explanation and demonstration of the regex here: http://regex101.com/r/eW6mZ0

Upvotes: 1

ashes999
ashes999

Reputation: 10163

If you want to extract the URL, just find the last instance of http, and take the substring:

String secondUrl = firstUrl.substring(firstUrl.lastIndexOf("http"));

Upvotes: 2

A Paul
A Paul

Reputation: 8251

Try this. "str" is the url string

System.out.println(str.substring(str.lastIndexOf("http:")));

Upvotes: 2

Bohemian
Bohemian

Reputation: 425198

Remove everything up to "http://" not found at the start:

String url2 = str.replaceAll("(?i).+(?=https?://)", "");

This will work case insensitively and match http or https protocols.

Upvotes: 2

Related Questions