使用 gsub R 删除所有特定的 html 标签

Remove all specific html tags using gsub R

我有一个像

这样的字符串
txt<-"text text text <div><div><script>xxxx</script></div><scrip>yyyyy</script>text </div><script>zzzzzz</script>"

我想删除所有脚本标签及其内容。

"text text text <div><div></div>text </div>"

我试过了

gsub("<script.*?>(.*)<\/script>", "", txt)

你能给我们一个很好的教程来学习 R 的快速正则表达式吗

提前致谢

我想我找到了

gsub("<script>[^</script>^<script>]+</script>", "", txt)

你第一次尝试贪婪点匹配注定要失败,因为贪婪匹配不能确保最短匹配(好吧,惰性匹配也不能),而且只会匹配中间所有必要的文本。

最近一次使用 <script>[^</script>^<script>]+</script> 的尝试也无效,因为 [^</script>^<script>]+ 匹配除 </s 以外的 1 个或多个字母, cript>^。显然这不是您需要的。

从问题本身抽象出来,可以使用正则表达式从文本中删除大块来处理任何纯文本文件

当我们需要匹配一些不相同的标记(或定界符)之间的子字符串时,我们可以使用展开循环技术 带有支持 lookaheads.

类 Perl 正则表达式

这是适用于任何大小的纯文本的工作代码:

txt<-"text text text <div><div><script>xxxx</script></div><script>yyyyy</script>text </div><script>zzzzzz</script>"
gsub("<script\b[^<]*>[^<]*(?:<(?!/script>)[^<]*)*</script>", "", txt, perl=T)
## [1] "text text text <div><div></div>text </div>"

regex demo can be seen here and here is the IDEONE demo.

基本上匹配:

  • <script\b[^<]*> - 任何开始的 <script> 标签,即使里面有属性(并不是说 < 不能出现在 HTML 属性中,因此 [^<]* 更安全使用比 [^<>]*[^>]*)
  • [^<]*(?:<(?!/script>)[^<]*)* - 展开的 (?s).*? 构造匹配除 </script>
  • 之外的任何文本
  • </script> - 关闭 </script> 标签