原贴 http://topic.csdn.net/u/20090104/13/3ac21d6a-847f-4400-8ea3-4d40e3c2093d.html?655735889回答得非常精彩,已经实现了我的要求,现在还有一个小小的问题,看能否帮我再改进一下。按照原贴给出的方法    public static void main(String[] args) {
        String str = "我有很多戒指,白金戒指,<a href=http://www.xxx.cn/img/1.gif alt='白金戒指'>,纯银戒指,<a href=http://www.xxx.cn/img/2.jpg alt='纯银戒指'>,总之很多很多戒指。;
        str = countReplace(str, "(戒指)", "<a href=http://www.xxx.cn/$1>$1</a>", 4);
        System.out.println(str);
    }执行后的结果:我有很多<a href=http://www.xxx.cn/戒指>戒指</a>,白金<a href=http://www.xxx.cn/戒指>戒指</a>,<a href=http://www.xxx.cn/img/1.gif alt='白金<a href=http://www.xxx.cn/戒指>戒指</a>'>,纯银<a href=http://www.xxx.cn/戒指>戒指</a>,<a href=http://www.xxx.cn/img/2.jpg alt='纯银戒指'>,总之很多很多戒指。我希望的结果是 我有很多<a href=http://www.xxx.cn/戒指>戒指</a>,白金<a href=http://www.xxx.cn/戒指>戒指</a>,<a href=http://www.xxx.cn/img/1.gif alt='白金戒指</a>'>,纯银<a href=http://www.xxx.cn/戒指>戒指</a>,<a href=http://www.xxx.cn/img/2.jpg alt='纯银戒指'>,总之很多很多<<a href=http://www.xxx.cn/戒指>戒指</a>。这两个的区别就是出现在<img> 图片说明中的关键词不被替换。只替换非html代码的部分.(因为一旦html代码被替换会导致整个结构发生错乱。)
比如这种情况str="<a href=''>某某戒指</a>"" 文本串中已经是链结了,则碰到这种情况不要再次替换。应该如何改写,谢谢!

解决方案 »

  1.   

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Test {    public static void main(String[] args) {
            String str = "a <a href=\"http://localhost:8080/test/戒指\">戒指</a>\n" +
             "<a href=\"http://localhost:8080/test/戒指\">戒指</a>\n" +
             "<a href=\"http://localhost:8080/test/戒指\">戒指</a>\n" +
             "<a href=\"http://localhost:8080/test/戒指\">戒指</a>\n" +
             "<img src=\"http://localhost:8080/test/戒指.gif\">\n" +
             "d\n" +
             "戒指\n" +
             "戒指\n" +
             "戒指\n" +
             "戒指\n" +
             "戒指\n" +
             "c";
            str = countReplace(str, "(?s)<([a-zA-Z][a-zA-Z0-9]*)\\b.*?</\\s*\\1>|<[a-zA-Z][a-zA-Z0-9]*\\b.*?/?>|(戒指)", "<a href=\"http://localhost:8080/test/$2\">$2</a>", 3);
            System.out.println(str);
        }
        
        private static String countReplace(String str, String regex, String replacement, int count) {
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(str);
            StringBuffer sb = new StringBuffer();
            int i = 0;
            int groupCount = matcher.groupCount();
            while(matcher.find() && (count < 0 || i < count)) {
                if(matcher.start(groupCount) > -1) {
                    matcher.appendReplacement(sb, replacement);
                    i++;
                }
            }
            matcher.appendTail(sb);
            return sb.toString();
        }
    }