Skip to content

Python RegEx find and replace | Example code

  • by

Use re.sub() method of the re module to replace the string that matches the RegEx (regular expression) in Python.

A Regular Expression (RE) is a special text string used for describing a search pattern.

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

Python regex find and replace Example

Simple example code.

You have to import the re module, and then we can use its sub() method.

Find all small letter before @ and replace with “ONE”.

import re

str1 = '[email protected]'

print(re.sub('[a-z]*@', 'ONE@', str1))

Output:

Python RegEx find and replace

Regular expression or RegEx in Python is denoted as RE (REs, regexes, or regex pattern) are imported through re module.

IdentifiersModifiersWhite space charactersEscape required
\d= any number (a digit)\d represents a digit.Ex: \d{1,5} it will declare digit between 1,5 like 424,444,545 etc.\n = new line. + * ? [] $ ^ () {} | \
\D= anything but a number (a non-digit)+ = matches 1 or more\s= space
\s = space (tab,space,newline etc.)? = matches 0 or 1\t =tab
\S= anything but a space* = 0 or more\e = escape
\w = letters ( Match alphanumeric character, including “_”)$ match end of a string\r = carriage return
\W =anything but letters ( Matches a non-alphanumeric character excluding “_”)^ match start of a string\f= form feed
. = anything but letters (periods)| matches either or x/y—————–
\b = any character except for new line[] = range or “variance”—————-
\.{x} = this amount of preceding code—————–

Do comment if you have any doubts and suggestions on this Python RegEx example code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading