java 正则表达式替换img标签的src路径

需求:由于系统切换,要求将存在数据库中的网页内容中的img标签的src属性进行修补,举例:

content="<p><img title=\"122444234\" src=\"/files/post/122444234.jpg\"/><p>其他字符";

要求替换后为:

content="<p><img title=\"122444234\" src=\"http://xxx.xxx.com/files/post/122444234_500.jpg\" /><p>其他字符";

 

 

使用正则即可解决,代码如下(ApiUtil.java静态方法)

Java代码   收藏代码
  1. /** 
  2.      * 将img标签中的src进行二次包装 
  3.      * @param content 内容 
  4.      * @param replaceHttp 需要在src中加入的域名 
  5.      * @param size 需要在src中将文件名加上_size 
  6.      * @return 
  7.      */  
  8.     public static String repairContent(String content,String replaceHttp,int size){  
  9.         String patternStr="<img\\s*([^>]*)\\s*src=\\\"(.*?)\\\"\\s*([^>]*)>";  
  10.         Pattern pattern = Pattern.compile(patternStr,Pattern.CASE_INSENSITIVE);  
  11.         Matcher matcher = pattern.matcher(content);  
  12.         String result = content;  
  13.         while(matcher.find()) {  
  14.             String src = matcher.group(2);  
  15.             logger.debug("pattern string:"+src);  
  16.             String replaceSrc = "";  
  17.             if(src.lastIndexOf(".")>0){  
  18.                 replaceSrc = src.substring(0,src.lastIndexOf("."))+"_"+size+src.substring(src.lastIndexOf("."));  
  19.             }  
  20.             if(!src.startsWith("http://")&&!src.startsWith("https://")){  
  21.                 replaceSrc = replaceHttp + replaceSrc;  
  22.             }  
  23.             result = result.replaceAll(src,replaceSrc);  
  24.         }   
  25.         logger.debug(" content == " +content);  
  26.         logger.debug(" result == " + result);  
  27.         return result;  
  28.     }  

 测试代码:

Java代码   收藏代码
  1. public static void main(String[] args) {  
  2.         String content = "<p><img  title=\"10010001\" src=\"/files/post/10010001.gif\" width=\"200\" height=\"300\" />" +  
  3.                 "</p><p><img  title=\"10010002\" src=\"/files/post/10010002.gif\" width=\"500\" height=\"300\" /><p>&nbsp;</p>"+  
  4.                 "</p><p><img  title=\"10010003\" src=\"/files/post/10010003.gif\" width=\"600\" height=\"300\" /><p>&nbsp;</p>";  
  5.         String replaceHttp = "http://www.baidu.com";  
  6.         int size = 500;  
  7.         String result = ApiUtil.repairContent(content, replaceHttp, size);  
  8.         System.out.println(result);  
  9.     }  
 

关键在于正则表达式:<img\\s*([^>]*)\\s*src=\\\"(.*?)\\\"\\s*([^>]*)>

特别是 ([^>]*) 不能用.*代替,否则只会从<img匹配到字符串最后一个">"符号为止,如果每个src的内容不一样,就只会替换最后一个src


参考链接:http://senon.iteye.com/blog/1591522

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值