How to Remove HTML Tags in Python with Regex

Strips all HTML tags from a string using a regular expression and cleans extra whitespace.

Easy Python 3.9+ Aug 9, 2026 Strings & text 13 views 0 copies

Python code

14 lines
Python 3.9+
import 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

stdout
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

  1. Use `re.compile(r'<[^>]+>')` and then call `pattern.sub('', text)` for reuse
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.