【正则】匹配头尾,并且中间不能有特定字符串

前端之家收集整理的这篇文章主要介绍了【正则】匹配头尾,并且中间不能有特定字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

缘由:

  开发Flex时调用到SWC文件的类库,想通过注释catalog.xml的script标签屏蔽一部分类包,然后自己重写。但是由于标签过多,手动注释只会累死人,只能用正则替换来注释script标签

替换内容

  1. <script name="com\error......>
  2.  
  3.   <dep ....../>
  4.  
  5.   <dep ....../>
  6.  
  7. </script>
  8.  
  9. <script name="com\warn......>
  10.  
  11.   <dep ....../>
  12.  
  13.   <dep ....../>
  14.  
  15. </script>
  16.  
  17. <script name="com\error......>
  18.  
  19.   <dep ....../>
  20.  
  21.   <dep ....../>
  22.  
  23. </script>

匹配逻辑:

  1.以<script开头

  2.以</script>结尾

  3.中间必须包含name="com\error字串

  4.中间不包含字串script


正确正则表达式:
  1. <(script)( name="com)(/error)(\b((?!\1).*?)+\b)(.*?)(</\1>)
正则不解释了,匹配逻辑有所不同的请自行分析参考。

正确替换内容
  1. <!--<$1$2$3$6$7-->


正确替换结果:
  1. <!--<script name="com\error......>
  2.  
  3.   <dep ....../>
  4.  
  5.   <dep ....../>
  6.  
  7. </script>-->
  8.  
  9.  
  10. <script name="com\warn......>
  11.  
  12.   <dep ....../>
  13.  
  14.   <dep ....../>
  15.  
  16. </script>
  17.  
  18.  
  19.  
  20. <!--<script name="com\error......>
  21.  
  22.   <dep ....../>
  23.  
  24.   <dep ....../>
  25.  
  26. </script>-->


之前我在网上找到很多的正则,都是有问题的。
错误替换结果:
  1. <!--<script name="com\error......>
  2.  
  3.   <dep ....../>
  4.  
  5.   <dep ....../>
  6.  
  7. </script>
  8.  
  9. <script name="com\warn......>
  10.  
  11.   <dep ....../>
  12.  
  13.   <dep ....../>
  14.  
  15. </script>
  16.  
  17.  
  18. <script name="com\error......>
  19.  
  20.   <dep ....../>
  21.  
  22.   <dep ....../>
  23.  
  24. </script>-->
可以看到,上面匹配时把"com\warn"的script标签也注释掉了,因为这个正则匹配的只是头尾,中间没有排除掉script标签的单词,这是贪婪模式下的匹配结果。

猜你在找的正则表达式相关文章