Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中使用正则表达式删除HTML注释_Python_Regex - Fatal编程技术网

如何在Python中使用正则表达式删除HTML注释

如何在Python中使用正则表达式删除HTML注释,python,regex,Python,Regex,我想从HTML文本中删除HTML注释 <h1>heading</h1> <!-- comment-with-hyphen --> some text <-- con --> more text <hello></hello> more text 标题一些文本更多文本更多文本 应导致: <h1>heading</h1> some text <-- con --> more text &l

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

<h1>heading</h1> <!-- comment-with-hyphen --> some text <-- con --> more text <hello></hello> more text
标题一些文本更多文本更多文本
应导致:

<h1>heading</h1> some text <-- con --> more text <hello></hello> more text
标题一些文本更多文本更多文本

终于想到了这个选项:

re.sub(“()”,“,”,t)


添加
使搜索不贪婪,并且不会合并多个注释标记。

您可以尝试使用此正则表达式

您不应该忽略回车符

re.sub("(<!--.*?-->)", "", s, flags=re.DOTALL)
re.sub(“()”,“”,s,flags=re.DOTALL)

不要使用正则表达式。改用XML解析器,标准库中的解析器就足够了

from xml.etree import ElementTree as ET
html = ET.parse("comments.html")
ET.dump(html) # Dumps to stdout
ET.write("no-comments.html", method="html") # Write to a file
html=re.sub(r“”,html)
re.sub基本上找到匹配的实例并替换为第二个参数。对于这种情况,
匹配以
开头的任何内容。点和?表示任何内容,\s和\n添加多行注释的情况。

re.sub((?s)”,“”,s)

re.sub(“,”,s,flags=re.DOTALL)

在有限的已知HTML集上使用正则表达式可能是合适的。然而,你应该知道,有无数的情况下,它将打破,它通常不建议。相关:为什么在这个问题上的否决票?如果你正在研究一个“已知的HTML集”,这是一个合法的问题。考虑使用一个特定的类库,比如漂亮的汤,像其他的问题解决方法一样:为什么我们不应该去除马车的回报?另一个答案缺少flags=re.multilitially应该是
re.DOTALL
,而不是
re.MULTILINE
。在
上匹配
\n
的是
re.DOTALL
,您的正则表达式匹配得太多了--请注意,问题中有一个示例“”,它不是HTML注释。@GregLindahl此正则表达式不匹配“”,并返回了预期的结果。这不会匹配内部带有HTML标记的注释,就像这是一个好建议一样,XML解析器的性能比这种正则表达式慢得多。欢迎使用!如果OP能自己理解你的代码,他可能不会问。请解释它的作用,以便为那些需要查找正则表达式的人提供价值。
html = re.sub(r"<!--(.|\s|\n)*?-->", "", html)
re.sub("<!--.+?-->", "", s, flags=re.DOTALL)