咱們知道經過正則表達式能夠實現對字符的匹配,正好項目中有個須要去掉圖片url的域名部分,好比:http://xxx.yyy.cn/aa/bb.jpg,去掉後爲aa/bb.jpg。這個用正則表達式能夠輕鬆實現。html
表達式以下:java
^((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。url
簡要說明:spa
()中表示一個子表達式,code
| 或關係,好比這裏匹配http://或https://regexp
? 表示匹配 0 次或一次。 也就是若是要匹配 xxx.yyy.cn/aa/bb.jpg 這個連接匹配的結果也是 aa/bb.jpghtm
{n,m}限定表達式,最少n次,最大m次。n<=mblog
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