Python re.sub() Method

Python re.sub() method “returns a string where the replace string replaces all matching occurrences of the specified pattern.”

Syntax

re.sub(pattern, replacement, string, count=0, flags=0)

Parameters

  1. pattern: It is a regular expression that you want to match.
  2. replacement: It is a replacement string.
  3. string: It is an input.
  4. count: It defines the maximum number of matches the re.sub() method should replace.
  5. flags: It is an argument that modifies the standard behavior of the pattern.

Return value

The re.sub() method searches for the pattern in the string and replaces the matched strings with a replacement string.

How to Use the re.sub() Method

To use the re.sub() method, import the re module.

import re

Define a string in which you need to substitute a substring.

str = 'abel@xxx.com selena@yyy.com benny@zzz.com'

In this example, we must replace all the substrings before @ character with the TONI substring.

import re

str = 'abel@xxx.com selena@yyy.com benny@zzz.com'

print(re.sub('[a-z]*@', 'TONI@', str))

Output

TONI@xxx.com TONI@yyy.com TONI@zzz.com

Getting a plain phone number using the re.sub() method

Using the regex.sub() method, you can get a plain phone number from a formatted string.

import re

phone_num = "(212)-456-7890"
pattern = "\D"
output = re.sub(pattern, "", phone_num)

print(output)

Output

2124567890

Replacing multiple substrings with the exact string

To replace multiple substrings with the same string in Python, use the re.sub() method.

If you are unfamiliar with regular expressions, embed a string with [ ] to match any character.

It can be used to replace several multiple characters with the same string.

import re

str = 'abel@xxx.com selena@yyy.com benny@zzz.com'

print(re.sub('[ben]', '1', str))

Output

a11l@xxx.com s1l11a@yyy.com 1111y@zzz.com

Replacing using the matched part

If part of the pattern is enclosed in () (rounded brackets), you can use the string that matches the part enclosed in () in the new string.

import re

str = 'abel@xxx.com selena@yyy.com benny@zzz.com'

print(re.sub('([a-z]*)@', '\\1-123@', str))

Output

abel-123@xxx.com selena-123@yyy.com benny-123@zzz.com

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.