我們知道通過正則表達式可以實現對字符的匹配,正好項目中有個需要去掉圖片url的域名部分,比如:http://xxx.yyy.cn/aa/bb.jpg,去掉后為aa/bb.jpg。這個用正則表達式可以輕松實現。
表達式如下:
^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}(/)
該表達式可以匹配以http://或者https://開頭且支持域名中有中划線的情況,並且會匹配到域名后的第一個/.
也就是我們開題說的替換完的結果就是 aa/bb.jpg。
簡要說明:
()中表示一個子表達式,
| 或關系,比如這里匹配http://或https://
? 表示匹配 0 次或一次。 也就是如果要匹配 xxx.yyy.cn/aa/bb.jpg 這個鏈接匹配的結果也是 aa/bb.jpg
{n,m}限定表達式,最少n次,最大m次。n<=m
java處理:
public static void main(String[] args) { String pattern = "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"; Pattern p = Pattern.compile(pattern); String line = "https://xxx.yyy.cn/aa/bb.jpg"; Matcher m = p.matcher(line); if(m.find()){ //匹配結果 System.out.println("=" + m.group()); } //替換 System.out.println(line.replaceAll(pattern, "")); }
參考:http://www.cnblogs.com/LCX/archive/2008/07/16/1244481.html
http://www.runoob.com/regexp/regexp-syntax.html