在做項目的過程中,需要將一段html代碼中的img標簽中的src屬性值批量替換成其他對應的值。
如下一段代碼
<!DOCTYPE html>
<html>
<head>
<meta charse="utf-8">
<title>demo</title>
<style>
img{
width: 200px;
}
</style>
</head>
<body>
![](http://upload-images.jianshu.io/upload_images/765812-0c17fe5db8bfa3b9.JPG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](http://upload-images.jianshu.io/upload_images/765812-0c17fe5db8bfa3b9.JPG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](http://upload-images.jianshu.io/upload_images/765812-0c17fe5db8bfa3b9.JPG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](http://upload-images.jianshu.io/upload_images/765812-0c17fe5db8bfa3b9.JPG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
</body>
</html>
經(jīng)過處理需要變成如下一段html片段
<!DOCTYPE html>
<html>
<head>
<meta charse="utf-8">
<title>demo</title>
<style>
img{
width: 200px;
}
</style>
</head>
<body>
![](http://dogwhere.b0.upaiyun.com/topic/3b473ccb822f4354823c07a8addf18667.JPG)
![](http://dogwhere.b0.upaiyun.com/topic/3b473ccb822f4354823c07a8addf18668.JPG)
![](http://dogwhere.b0.upaiyun.com/topic/3b473ccb822f4354823c07a8addf18669.JPG)
![](http://dogwhere.b0.upaiyun.com/topic/3b473ccb822f4354823c07a8addf18670.JPG)
</body>
</html>
解決這個問題的關鍵就是一個正則表達式他嫡,如下是處理的完整代碼
//匹配img標簽的正則表達式
String regxpForImgTag = "<img\\s[^>]+/>";
Pattern pattern = Pattern.compile(regxpForImgTag);
Matcher matcher = pattern.matcher(result);
while (matcher.find()) {
String temp = matcher.group();
String tempUrl = temp.substring(temp.indexOf("src=") + 5);
tempUrl =tempUrl.substring(0, tempUrl.indexOf("\""));
String urlResult = "another url";
result = result.replace(temp, urlResult);
}