工具方法:
public static String getValueByKeyInHtml(String src, String key) {
Pattern pattern = Pattern.compile("(?:" + key + "\\s*=\\s*)" + "['\"](.*?)['\"]");
Matcher matcher = pattern.matcher(src);
if (matcher.find()) {
return matcher.group().replaceAll(key + "\\s*=\\s*", "").replaceAll("\"", "");
}
return null;
}
示例:
NiceUtil.getValueByKeyInHtml("<a href="https://www.baidu.com/">","href");
//會返回 https://www.baidu.com/
正則講解:
重點是 .*? 的用法。其他都很簡單。
關於 .*? 的意思,
. : 任意字符(不包括回車)
*: 零個或任意個
? : 非貪婪模式
所以連起來就是:取儘量少的任意字符。
但它一般不會這麼單獨寫,大多會這麼用:
.*?a
意思就是取前面任意長度的字符,到“第一個a” 出現。
以前一直覺得是?加在第二個 ['\"]後面,這是不對的,應該是匹配儘量少的字符,直到 ['\"]出現。
額。不理解的話,就跟我一樣就把 .*? 的用法背過吧。