Need to do in Java with regex for conditional replacement (see the sample below if do it in javascript). Couldn't find a easy way to do it with Java. Anyone knows if there is equivalent function/callback to do it in Java?
The problem is on Android it needs to find a img tag match with certain token in it, and if that tag is found the src part need to be modified. The problem is the img tag may also have different attributes and they should be kept. And they could be located in random place inside the img tag. And the src is unknown but only know it should be modified. So it is looking for the token attribute in img tag and modify src part in it.
(img attribute1 token="this is the token" style="width:100px;......" src="http://......" someOtherAttributes /)
or
(img src="http://......" attribute1 token="this is the token" someOtherAttributes style="width:100px;......" /)
The result would be only the src is modified, like (img src="http://....../pathabc" attribute1 token="this is the token" someOtherAttributes style="width:100px;......" /)
In javascript you may want do
var passedInToken = "this is the token";
var srcPath = "/pathabc";
var regex = new RegExp("(?:<img\\s)([^<]*)(?:token=\""+passedInToken+"\"\\s*)([^>]*)>", "gi");
var foundToken = regex.test(testSourceHtmlString);
if (foundToken) {
var testSourceHtmlString = testSourceHtmlString.replace(regex, function(matchStr, grp1, grp2){
var attributeStrToBeReserved = grp1+" "+grp2;
var findSrcRegex = new RegExp("(src=\".*?\")");
if (findSrcRegex.test(attributeStrToBeReserved)){
attributeStrToBeReserved = attributeStrToBeReserved.replace(srcRegex, function(match, g1){
return g1 + srcPath;
});
}
return "<img token=\""+passedInToken+"\""+attributeStrToBeReserved+">";
});
}