[英]How to remove HTML comments using Regex in Python
我想从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("(<!--.*?-->)", "", s, flags=re.DOTALL)
最后想出了这个选项:
re.sub("(<!--.*?-->)", "", t)
添加?
使搜索非贪婪,并且不会组合多个注释标记。
html = re.sub(r"<!--(.|\s|\n)*?-->", "", html)
re.sub基本上找到匹配的实例并用第二个参数替换。 对于这种情况, <!--(.|\\s|\\n)*?-->
匹配以<!--
开头并以-->
结尾的任何内容。 点和? 意味着什么,\\ s和\\ n添加了多行评论的案例。
不要使用正则表达式。 使用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
re.sub("(?s)<!--.+?-->", "", s)
要么
re.sub("<!--.+?-->", "", s, flags=re.DOTALL)
你可以试试这个正则表达式<![^<]*>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.