如何在Python中使用Regex删除HTML注释

Rus*_*hta 5 python regex

我想从HTML文本中删除HTML注释

<h1>heading</h1> <!-- comment-with-hyphen --> some text <-- con --> more text <hello></hello> more text
Run Code Online (Sandbox Code Playgroud)

应导致:

<h1>heading</h1> some text <-- con --> more text <hello></hello> more text
Run Code Online (Sandbox Code Playgroud)

小智 6

您不应忽略回车。

re.sub("(<!--.*?-->)", "", s, flags=re.DOTALL)
Run Code Online (Sandbox Code Playgroud)

  • 实际上应该是“ re.DOTALL”,而不是“ re.MULTILINE”。是与`.`上的\ n匹配的re.DOTALL。 (4认同)

Sha*_*awn 5

html = re.sub(r"<!--(.|\s|\n)*?-->", "", html)
Run Code Online (Sandbox Code Playgroud)

re.sub 基本上找到匹配的实例并替换为第二个参数。对于这种情况,<!--(.|\s|\n)*?-->匹配以 开头<!--和结尾的任何内容-->。点和?表示任何内容,\s 和 \n 添加多行注释的情况。


Rus*_*hta 3

最后想出了这个选项:

re.sub("(<!--.*?-->)", "", t)

添加?使得搜索非贪婪并且不会组合多个评论标签。