需求:將網頁分享給其他人,JShare的分享模板如下:
其中有標題(紅色)、內容(黃色)、圖片(綠色),但是接口中沒有給圖片的URL,而html格式的內容中有<img src="http://……">標籤,需要去內容中自己提取第一張圖片作爲分享的圖標,如下:
所以,這個時候我們的需求就一目瞭然了:用正則表達式從繁雜的內容中找到我們需要的圖片。
解決:
1、正則表達式:(http://jszx-jxpt.cuit.edu.cn/JavaAPI/java/util/regex/Pattern.html)官方API,供查詢瞭解
2、代碼查找:
一、先找到<img src="">標籤,用到的正則表達式("<img.*?>")
代碼如下:
public static List<String> getMatchString(){
List<String> pics = new ArrayList<>(); // 因文件可能有多張圖片,故用集合來存儲結果
Pattern compile = null;
if (isDistinguish){ // isDistinguish:是否區分大小寫
compile = Pattern.compile("<img.*?>"); // "<img.*?>" : 獲取標籤的正則
}else{
compile = Pattern.compile("<img.*?>", Pattern.CASE_INSENSITIVE);
}
Matcher matcher = compile.matcher(string); // string:後臺返的內容,圖片就是從中提取的
while (matcher.find()){
String img = matcher.group();
pics.add(img);
}
return pics;
}
運行,得到結果如下:
可以看出,本文有三張圖片
二、再拿到標籤中的地址,直接可以使用,代碼如下:
List<String> img_url = new ArrayList<>();
/**
* img : 上面打印的標籤內容,將它直接提取爲我們要的http……
*
* "\"http?(.*?)(\"|>|\\s+)" : 獲取src中 "" 圖片地址的正則
*/
Matcher m = Pattern.compile("\"http?(.*?)(\"|>|\\s+)").matcher(img);
m.find();
String url = m.group()
img_url.add(url.substring(1, url.length()-1));
運行,得到的結果如下:
可以看出,直接光禿禿的圖片地址裸露在臉前,可以直接用了
最後貼出完整代碼:
/**
* regex:獲取<img src="">標籤的正則("<img.*?>")
* string:提取圖片標籤的內容
* isDistinguish:是否區分大小寫
*/
public static List<String> getMatchString(String regex, String string, boolean isDistinguish){
List<String> pics = new ArrayList<>();
Pattern compile = null;
if (isDistinguish){
compile = Pattern.compile(regex);
}else{
compile = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
}
Matcher matcher = compile.matcher(string);
while (matcher.find()){
String img = matcher.group();
// pics.add(img); // 如果只需要標籤,那到這一步就可以了,如果直接需要圖片URL,copy代碼到最後
/**
* reg_html_img_src_http: 獲取src中 "" 圖片地址的正則("\"http?(.*?)(\"|>|\\s+)")
*
* 獲取標籤中src的正則表達式("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)")
*/
Matcher m = Pattern.compile(reg_html_img_src_http).matcher(img);
m.find();
String group = m.group();
pics.add(group.substring(1, group.length() - 1));
}
return pics;
}