Remove characters matching Regex from a String in Python

avatar

Borislav Hadzhiev

Last updated: Aug 21, 2022

banner

Photo from Unsplash

Remove characters matching Regex from a String in Python #

Use the re.sub() method to remove the characters that match a regex from a string, e.g. result = re.sub(r'[!@#$]', '', my_str). The re.sub() method will remove the matching characters by replacing them with empty strings.

main.py
import re my_str = '!apple @banana #kiwi $melon' result = re.sub(r'[!@#$]', '', my_str) print(result) # 👉️ 'apple banana kiwi melon' result = re.sub(r'[^!@#$]', '', my_str) print(result) # 👉️ '!@#$' # -------------------------------------- # 👇️ using generator expression and str.join() characters_to_remove = '!@#$' result = ''.join(char for char in my_str if char not in characters_to_remove) print(result) # 👉️ 'apple banana kiwi melon'

The first example uses the re.sub() method to remove the characters that match a regular expression from a string.

The re.sub method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.

main.py
import re my_str = '1apple, 2apple, 3banana' result = re.sub(r'[0-9]', '', my_str) print(result) # 👉️ 'apple, apple, banana' result = re.sub(r'[a-zA-Z]', '', my_str) print(result) # 👉️ '1, 2, 3'

If the pattern isn't found, the string is returned as is.

If you have specific characters you'd like to remove, add them between square brackets.

main.py
import re my_str = '!apple @banana #kiwi $melon' result = re.sub(r'[!@#$]', '', my_str) print(result) # 👉️ 'apple banana kiwi melon' result = re.sub(r'[^!@#$]', '', my_str) print(result) # 👉️ '!@#$'

The square brackets [] are used to indicate a set of characters.

The first example removes the specified characters by replacing them with empty strings.

The second example uses the caret ^ symbol.

The caret ^ at the beginning of the set means "NOT". In other words, match all characters that are NOT !, @, # and $.

Alternatively, you can use a generator expression with the str.join() method.

main.py
my_str = '!apple @banana #kiwi $melon' characters_to_remove = '!@#$' result = ''.join(char for char in my_str if char not in characters_to_remove) print(result) # 👉️ 'apple banana kiwi melon'

We used a generator expression to iterate over the string.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the character is not one of the characters to be removed and return the result.

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

x not in s returns the negation of x in s.
main.py
print('hi' not in 'apple') # 👉️ True print('app' not in 'apple') # 👉️ False

The last step is to use the str.join() method to join the remaining strings.

main.py
my_str = '!apple @banana #kiwi $melon' characters_to_remove = '!@#$' result = ''.join(char for char in my_str if char not in characters_to_remove) print(result) # 👉️ 'apple banana kiwi melon'

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

We used an empty string as the separator between the elements because we want to join the remaining characters without a separator.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.