如题
例如
<html
<script
<!--不可以删除-->
/script><!--需要删除-->
<!--需要删除--><script
<!--不可以删除-->
/script><!--需要删除-->
<!--需要删除-->/html>用一个正则表达式应该怎么写才能用replace方法
<html
<script
<!--不可以删除-->
/script>
<script
<!--不可以删除-->
/script>
/html>
例如
<html
<script
<!--不可以删除-->
/script><!--需要删除-->
<!--需要删除--><script
<!--不可以删除-->
/script><!--需要删除-->
<!--需要删除-->/html>用一个正则表达式应该怎么写才能用replace方法
<html
<script
<!--不可以删除-->
/script>
<script
<!--不可以删除-->
/script>
/html>
我能力问题,只能用3个replaceAll来完成...真不好意思
想了很久都只能用3个replace来写...
<html ---<script中间的注释
/script> ----<script中间的注释
/script>-----/html>中间的注释
分开取缔...真的没什么办法了....
这个是我写的正则表达式
-------------------------------------------
例子
<!--a--->
<script
<!--a--->
/script>
<!--a--->
<!--b--->
<script
<!--a--->
/script>
可以过滤成功
--------------------------------------------
但是
<!--a--->
<!--a--->
<!--a--->
<!--b--->
只能过滤<!--b---> (最后一句)
---------------------------------------------
不知道为什么
/script> 没有“<”?
String str =
"<html\n" +
" 111111111\n" +
" <!--不要保留-->\n" +
" 222222222\n" +
" <!--不要保留-->\n" +
" <script\n" +
" 3333333333\n" +
" <!--要保留-->\n" +
" <!--要保留-->\n" +
" 4444444444\n" +
" <!--要保留-->\n" +
" /script>\n" +
" 555555555\n" +
" <!--不要保留-->\n" +
" <!--不要保留-->\n" +
" 666666666\n" +
" <script\n" +
" <!--要保留-->\n" +
" 777777777\n" +
" <!--要保留-->\n" +
" 888888888\n" +
" /script>\n" +
" <!--不要保留-->\n" +
" <!--不要保留-->\n" +
" 99999999\n" +
" <!--不要保留-->\n" +
" aaaaaaaa\n" +
" <!--不要保留-->\n" +
" bbbbbbbb\n" +
"/html>\n";
System.out.println(str);
System.out.println("-------------");
// String regex = "(?s)(<script.*?/script>)?(?:<!--.*?-->)?"; // 保留删除的那一行
String regex = "(?s)(<script.*?/script>)?(?: *<!--.*?--> *\\n)?"; // 不保留删除的那一行
str = str.replaceAll(regex, "$1");
System.out.println(str);
}
}
str = str.replaceAll(regex, "$1");中的$1的作用
还有就是我用pattern不能匹配<html /html>
即“(xxx)”,而“(?xxx)”之类的是非捕获组。Java 中可以保存 $1~$9 共计九个捕获组的内容,$ 结构的只能在替换
参数中使用。
“还有就是我用pattern不能匹配 <html /html>”这个我没看明白。
(非匹配组)不需要保留 请问 这句话是什么意思?str = str.replaceAll(regex, "");我也是用这个来替换不在script中所有html注释regex: (?s)(<script(.|\n)*?/script>)?(?:<!--(.|\n)*?-->*\n)? source: <!--1-->
<script asdasd>
<!--0-->
</script>
结果: <!--1-->
<script asdasd><!--0--></script>
匹配结果有三个,不知道为什么
我用的是code Architects Regex tester
?: *的含义?谢谢!
以的,但是没有必要,因为捕获组在匹配完成后会在内存中保留下来以备再次的反向引用,
由于这一块我们是需要扔掉的,所以就不要去浪费内存让它保留,使用非捕获组的结构就是
纯粹的一组,并不会在内容中保留,这样做只是降低内存占用。想了解更多关于捕获组的知识,可以看看我的一个帖子,里面有个 Java Tutorial 中关于
正则表达式教程的译稿下载和其他的一些资源,有兴趣的话可以看看。http://topic.csdn.net/u/20080306/17/f37a1818-3968-49b4-8f79-e5564486d63e.html