parthpar
parthpar

Reputation: 218

Replace and modify String using regex in java

I have a part of HTML from a website in the below String format:

srcset=" /tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 200w, /tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 338w, /tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 445w, tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 542w, /tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 750w"

I want to add http://tesla.com in front of all the urls in the srcset element like http://tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 750w

I believe this could be done using regex, but I am not sure.

How do I do this using Java if I have multiple srcset elements in a html string variable, and I want to replace all of the srcset url.'s and add the server url in front?

Note: The /tesla_theme will not be consistent, so I cannot use replaceAll, instead, i will have to use regex.

Upvotes: 0

Views: 69

Answers (1)

You can simply use String Class replace method as below, It will replace all "/_tesla" in the given String. No special regex required unless you have a kind of pattern instead of "/tesla"

String srcset=" /tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 200w, /tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 338w, /tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 445w, tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 542w, /tesla_theme/assets/img/homepage/mobile/[email protected]?20170808 750w";

String requiredSrcSet = srcset.replace("/tesla_", "http://tesla_");

Upvotes: 1

Related Questions