How to Remove HTML Tags in Python with Regex
Strips all HTML tags from a string using a regular expression and cleans extra whitespace.
Python code
14 linesimport re
def remove_html_tags(text: str) -> str:
"""Remove all HTML tags from the given text using regex."""
# Remove opening and closing tags
clean = re.sub(r'<[^>]+>', '', text)
# Remove any extra whitespace left behind
clean = re.sub(r'\s+', ' ', clean).strip()
return clean
if __name__ == "__main__":
sample = "<h1>Hello, <b>World</b>!</h1><p>This is <i>Python</i>.</p>"
result = remove_html_tags(sample)
print(result)
Output
Hello, World! This is Python.
How it works
This pattern r'<[^>]+>' matches any character between < and > that is not >, effectively catching both opening and closing tags. The re.sub replaces every match with an empty string. After tags are removed, a second substitution collapses multiple whitespace characters into a single space and strip() trims leading/trailing spaces. This works for simple HTML without embedded > inside tag attributes or script/style content. For robust parsing, use an HTML parser like BeautifulSoup, but this regex is sufficient for quick text extraction.
Common mistakes
- Using `r'<.*?>'` which is equivalent to `r'<[^>]+>'` but may be slower on large strings
- Forgetting to collapse extra whitespace left after tag removal, producing run-on text
- Applying regex to malformed HTML with `>` inside attributes, causing incomplete tag removal
Variations
- Use `re.compile(r'<[^>]+>')` and then call `pattern.sub('', text)` for reuse
- For a more accurate but heavier approach, use `BeautifulSoup(text, 'html.parser').get_text()`
Real-world use cases
- Cleaning scraped web content before saving it into a text column for search indexing.
- Displaying a plain-text preview of an HTML email body inside a notification feed.
- Extracting readable text from HTML snippets in API payloads before sentiment analysis.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.