需求:由于系统切换,要求将存在数据库中的网页内容中的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静态方法)
- /**
- * 将img标签中的src进行二次包装
- * @param content 内容
- * @param replaceHttp 需要在src中加入的域名
- * @param size 需要在src中将文件名加上_size
- * @return
- */
- public static String repairContent(String content,String replaceHttp,int size){
- String patternStr="<img\\s*([^>]*)\\s*src=\\\"(.*?)\\\"\\s*([^>]*)>";
- Pattern pattern = Pattern.compile(patternStr,Pattern.CASE_INSENSITIVE);
- Matcher matcher = pattern.matcher(content);
- String result = content;
- while(matcher.find()) {
- String src = matcher.group(2);
- logger.debug("pattern string:"+src);
- String replaceSrc = "";
- if(src.lastIndexOf(".")>0){
- replaceSrc = src.substring(0,src.lastIndexOf("."))+"_"+size+src.substring(src.lastIndexOf("."));
- }
- if(!src.startsWith("http://")&&!src.startsWith("https://")){
- replaceSrc = replaceHttp + replaceSrc;
- }
- result = result.replaceAll(src,replaceSrc);
- }
- logger.debug(" content == " +content);
- logger.debug(" result == " + result);
- return result;
- }
测试代码:
- public static void main(String[] args) {
- String content = "<p><img title=\"10010001\" src=\"/files/post/10010001.gif\" width=\"200\" height=\"300\" />" +
- "</p><p><img title=\"10010002\" src=\"/files/post/10010002.gif\" width=\"500\" height=\"300\" /><p> </p>"+
- "</p><p><img title=\"10010003\" src=\"/files/post/10010003.gif\" width=\"600\" height=\"300\" /><p> </p>";
- String replaceHttp = "http://www.baidu.com";
- int size = 500;
- String result = ApiUtil.repairContent(content, replaceHttp, size);
- System.out.println(result);
- }
关键在于正则表达式:<img\\s*([^>]*)\\s*src=\\\"(.*?)\\\"\\s*([^>]*)>
特别是 ([^>]*) 不能用.*代替,否则只会从<img匹配到字符串最后一个">"符号为止,如果每个src的内容不一样,就只会替换最后一个src
参考链接:http://senon.iteye.com/blog/1591522