原贴:http://topic.csdn.net/u/20090104/16/80837e0c-2cbb-4daa-a9a2-9389ef2d3d87.html原贴的描述漏了一点,又要麻烦您了。就是我希望只是影响html结构的标签内的文字不做替换。其实在一个html中,一般来说也就是 <a href="">原词</a> <img src="" alt="原词">,更多的我还没有想到。而类似<P>...原词 </P> <div>...原词</div>中的是不需要去的。所以 原字符串 String str = "<P>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"</P>;
被<P></P> 或者<DIV><DIV> <p></p> <div></div> 扩起来的时候,不能被正常替换,而实际我是希望在这种情况下,仍然被替换,而不是所有html标签内都不做替换。我希望至少能保证段落标签<P>或者<DIV>扩起来的部分能被正常替换就可以了,更多情况暂不考虑了,麻烦您了。
"<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"</P>;
被<P></P> 或者<DIV><DIV> <p></p> <div></div> 扩起来的时候,不能被正常替换,而实际我是希望在这种情况下,仍然被替换,而不是所有html标签内都不做替换。我希望至少能保证段落标签<P>或者<DIV>扩起来的部分能被正常替换就可以了,更多情况暂不考虑了,麻烦您了。
import java.util.regex.Pattern;public class Test { public static void main(String[] args) {
String str = "<p>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</p>";
str = countReplace(str, "(?is)<((?!p|div)[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();
}
}非常不好意思,白天公司忙死了,只有晚上回家后有点时间上上 CSDN
str = countReplace(str, "(?is)<((?!p|div)[a-zA-Z][a-zA-Z0-9]*)\\b.*?</\\s*\\1>|<[a-zA-Z][a-zA-Z0-9]*\\b[^>]*/?>|(戒指)", "<a href=\"http://www.xxx.cn/list/$2\">$2</a>", 5);运行以后变成了
<P>我有很多<a href="http://www.xxx.cn/list/戒指">戒指</a>,白金<a href="http://www.xxx.cn/list/戒指">戒指</a>,<a href=http://www.xxx.cn/img/1.gif alt='白金<a href="http://www.xxx.cn/list/戒指">戒指</a>'>,纯银<a href="http://www.xxx.cn/list/戒指">戒指</a>,<a href=http://www.xxx.cn/img/2.jpg alt='纯银<a href="http://www.xxx.cn/list/戒指">戒指</a>'>,总之很多很多戒指。</P>Process exited with exit code 0.
我试了一下,img 中的“戒指”不管所面是否有 / 都没被替换掉啊?
所面是否有 / 都没被替换掉啊?我试了一下,img 中的“戒指”不管后面是否有 / 都没被替换掉啊?就连 JDK 1.5 中也有很多 bug,这种情况直到 JDK 6 才有所好转。