import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Replace04 {
    public static String replace(String html, String prefix) {
        Pattern p1 = Pattern.compile("(/)([\\w]+\\.(gif)|(jpg)|(png))",
                Pattern.CASE_INSENSITIVE);
        Matcher m1 = p1.matcher(html);
        StringBuffer buff = new StringBuffer();        while (m1.find()) {
            m1.appendReplacement(buff, "$1" + prefix + "$2");
        }
        m1.appendTail(buff);        return buff.toString();
    }    public static void main(String[] args) {
        String example = "... ...\n" +
                "<td class=\"f13\" background=\"../../images/bg032.gif\" height=\"19\">列表</td>\n" +
                "... ...\n" +
                "<td class=\"f12\" width=\"20\"> <div align=\"right\"> <img height=\"11\" width=\"11\" src=\"../img1/34.gif\"></div></td>\n" +
                "... ...";
        String prefix = "cf_";        System.out.println(replace(example, prefix));
    }
}[\\w] 的 [] 里面是文件名可用字符集
如果文件名中可以包括 % 和 - 的话, 可以改成 [\\w%-] 依此类推

解决方案 »

  1.   

    registered(已注册),非常感谢你!    我以前没用过正则表达式,你能给一些资料的链接么?
      

  2.   

    文档: http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
    经典: http://www.amazon.com/exec/obidos/ASIN/0596002890/qid=1094455092/sr=ka-1/ref=pd_ka_1/002-3814657-5600859#product-details
    参考: http://www.amazon.com/exec/obidos/ASIN/059600415X/qid=1094455168/sr=ka-2/ref=pd_ka_2/002-3814657-5600859#product-details
    没有选择的选择(本人对 SAMS 速成系列书籍向来没有好感, 不过这本好像还凑合): http://www.amazon.com/exec/obidos/ASIN/0672325667/qid=1094455168/sr=ka-3/ref=pd_ka_3/002-3814657-5600859最后两本书我有英文电子版, 如果需要请留下 email
    中文版没有