Python regex remove substring

How removing a substring with Python's re.sub works, when a plain string method is safer, and how to avoid broken spacing, Unicode marks and lost meaning.

To remove a substring with a regular expression in Python, you usually call re.sub with an empty replacement string. This review covers what that call changes in your text, when it is the right tool, and when it can damage text without any warning.

Is regex removal suitable for your task?

Use re.sub when the text you want to remove follows a pattern rather than a fixed spelling. Examples include order numbers, repeated whitespace, bracketed tags, or a word in any letter case. The main benefit is that one expression handles every variant. The main tradeoff is that a pattern can match more or less than you intended, and Python will not tell you. Matched text is simply absent from the new string. If the substring is fixed, or the data has its own structure, a plain string method or a dedicated parser is usually safer and easier to read.

Task | Recommended approach | Reason
Remove a fixed substring everywhere | str.replace(old, "") | No regex syntax to get wrong
Remove a fixed prefix or suffix once | str.removeprefix / str.removesuffix (Python 3.9+) | Only touches the start or end
Remove a fixed substring that contains symbols like ( ) . + ? | re.sub(re.escape(s), "", text) | Escaping keeps the symbols literal
Remove text matching a variable pattern | re.sub(pattern, "", text) | One expression covers all variants
Remove tags or fields from HTML, JSON or CSV | A parser for that format | Regex cannot reliably follow nesting or quoting rules

What the transformation actually changes

re.sub(pattern, repl, string, count=0, flags=0) scans the string from left to right. It replaces each non-overlapping match with repl and returns a new string. Python strings are immutable, so the original variable is unchanged unless you assign the result back to it. This changes the stored characters. It is different from hiding text visually, for example with CSS, and it does not reverse, mirror or restyle anything. The removed characters do not exist in the result.

import re

text = "Order #123 shipped"
clean = re.sub(r"#\d+\s*", "", text)
print(clean)   # Order shipped
print(text)    # Order #123 shipped  (original unchanged)

If the substring contains characters that have special meaning in regex, such as parentheses, dots or plus signs, pass it through re.escape so that it matches literally. Removing a word from the middle of a sentence often leaves two spaces behind. You can include the neighboring whitespace in the pattern to avoid this.

import re

s = "App (beta) v2"
print(re.sub(re.escape("(beta)"), "", s))   # 'App  v2'  (double space)
print(re.sub(r"\s*\(beta\)", "", s))        # 'App v2'

Matching too much is the most common failure. A bare word pattern also matches inside longer words, and adding \b word boundaries prevents that. A greedy .* runs to the last possible match on the line, while the non-greedy .*? stops at the first one.

import re

print(re.sub(r"cat", "", "concatenate the cat"))      # 'conenate the '
print(re.sub(r"\bcat\b", "", "concatenate the cat"))  # 'concatenate the '

print(re.sub(r"<.*>", "", "a <b> c <d> e"))   # 'a  e'      (greedy)
print(re.sub(r"<.*?>", "", "a <b> c <d> e"))  # 'a  c  e'   (non-greedy)

The count argument limits how many matches are removed. The flags argument changes matching behavior, for example re.IGNORECASE. Pass both as keyword arguments, because Python 3.13 deprecated passing them positionally.

import re

print(re.sub(r"-", "", "a-b-c", count=1))   # 'ab-c'
print(re.sub(r"\bdraft\b\s*", "", "Draft notes, final draft", flags=re.IGNORECASE))
# 'notes, final '

Unicode edge cases: combining marks and emoji

Regex works on code points, not on the characters a reader sees. An accented letter can be stored as one precomposed code point or as a base letter followed by a combining mark. Many emoji are sequences of several code points joined by zero-width joiners. Removing part of such a sequence leaves fragments that may render oddly. Character classes can also catch these marks: in Python's default Unicode mode, a combining mark is not a word character, so \W removes it.

import re
import unicodedata

decomposed = "cafe\u0301"   # e + combining acute accent
print(ascii(re.sub("e", "", decomposed)))     # 'caf\u0301'  (orphaned accent)
print(ascii(re.sub(r"\W", "", decomposed)))   # 'cafe'       (accent stripped)

composed = unicodedata.normalize("NFC", decomposed)
print(ascii(re.sub("e", "", composed)))       # 'caf\xe9'    (precomposed é does not match "e")

family = "\U0001F468\u200d\U0001F469\u200d\U0001F467"
print(ascii(re.sub("\U0001F469", "", family)))
# '\U0001f468\u200d\u200d\U0001f467'  (leftover joiners)

If your input may contain accented or non-Latin text, normalize it to one form, usually NFC, before you match. Then test patterns against both forms. The standard re module has no pattern for a whole user-perceived character. The third-party regex module supports \X for grapheme clusters, which can help when you must remove whole emoji or accented letters.

Will the result remain readable and usable after copying or sharing?

The output is ordinary text with no styling or hidden formatting. When you copy, paste, store or send it, the characters in the string are exactly what travels. Problems come from what the pattern removed and what it left behind, not from the transformation surviving transfer.

  • Spacing and punctuation: leftover double spaces, stray commas or empty brackets make the text harder to read and to search.
  • Broken characters: orphaned combining marks or zero-width joiners can render as odd symbols or invisible characters, and later edits may handle them unexpectedly.
  • Meaning: removing a word like "not" or a unit like "mg" changes what the text says. Review a sample of matches before running a removal on real data.
  • Search and indexing: text that has been removed can no longer be found by search, so keep the source if anyone may need to look up the original wording.
  • Editing and recovery: re.sub cannot be undone, so keep the original string or file when you transform for display, export or analysis.

Screen readers and other assistive technology read the characters that remain, so clean output should read like any other plain text. Leftover marks or joiners could be read aloud or skipped in ways that vary between tools. No tested evidence for specific screen readers, editors or platforms was available for this review, so check the cleaned text in the environments where it will actually be used.

Keep an unmodified plain-text copy whenever the removal is cosmetic, when the text is quoted or legally significant, or when another person or system may need the full wording.

A safe removal workflow

  • Choose the simplest tool that fits: a string method for fixed text, re.sub for patterns, a parser for structured formats.
  • Escape literal input with re.escape, especially when the substring comes from a user or a file.
  • Add word boundaries and include neighboring whitespace in the pattern where appropriate.
  • Normalize Unicode input before matching.
  • Use re.findall or re.finditer to preview the matches before you delete anything.
  • Test edge cases with assertions, and keep the original text.
import re
import unicodedata

def remove_pattern(text, pattern, flags=0):
    text = unicodedata.normalize("NFC", text)
    result = re.sub(pattern, "", text, flags=flags)
    return re.sub(r"\s{2,}", " ", result).strip()

print(re.findall(r"\bcat\b", "concatenate the cat"))   # ['cat']  preview first
assert remove_pattern("App (beta) v2", r"\(beta\)") == "App v2"
assert remove_pattern("concatenate the cat", r"\bcat\b") == "concatenate the"

The whitespace cleanup in this helper also turns line breaks and tabs into single spaces. Drop that step, or narrow it to spaces only, if your text's layout matters.

Evidence gaps

This review relies on documented Python behavior and on examples whose outputs follow from that behavior. It does not include performance measurements, comparisons with third-party tools beyond the \X feature mentioned above, or tests of how cleaned text displays in specific apps or assistive technologies.