5
votes

I want to remove HTML comments from an html text

<h1>heading</h1> <!-- comment-with-hyphen --> some text <-- con --> more text <hello></hello> more text

should result in:

<h1>heading</h1> some text <-- con --> more text <hello></hello> more text
6
Using regular expressions on a limited, known set of HTML may be appropriate. However, you should be aware that there are countless cases where it will break and it is generally not advised. - grc
Why the downvotes on the question? If you are working on a "known set of HTML" this was a legit question. - Rushabh Mehta
Consider using a HTML specific library like Beatiful Soup, like this other question-solutions suggests: stackoverflow.com/questions/23299557/… - hectorcanto

6 Answers

8
votes

You shouldn't ignore Carriage return.

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

Finally came up with this option:

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

Adding the ? makes the search non-greedy and does not combine multiple comment tags.

3
votes
html = re.sub(r"<!--(.|\s|\n)*?-->", "", html)

re.sub basically find the matching instance and replace with the second arguments. For this case, <!--(.|\s|\n)*?--> matches anything start with <!-- and end with -->. The dot and ? means anything, and the \s and \n add the cases of muti line comment.

1
votes

Don't use regex. Use an XML parser instead, the one in the standard library is more than sufficient.

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
1
votes
re.sub("(?s)<!--.+?-->", "", s)

or

re.sub("<!--.+?-->", "", s, flags=re.DOTALL)
0
votes

You could try this regex <![^<]*>