Menu Close

Replacing in Regular Expression Regex in Python …FcukTheCode.com

Basics of Regular Expressions in Python, check the link below ๐Ÿ‘‡ ๐Ÿ‘‡
Regular Expressions Regex basic in Python ๐Ÿ‘ˆ ๐Ÿ‘ˆ

Also with table of contents about symbols and their usage in Regex

Links for other methods like search, flags and pre-compiled patterns in regular expression scroll down
๐Ÿ‘‡ ๐Ÿ‘‡

Python makes regular expressions available through the re module.

Replacing in Regex Python

Replacements can be made on strings using re.sub .

Replacing strings

import re
print( re.sub(r"t[0-9][0-9]", "foo", "my name t13 is t44 what t99 ever t44") )

# Output: 'my name foo is foo what foo ever foo'

OUTPUT: my name foo is foo what foo ever foo

Using group references
Replacements with a small number of groups can be made as follows:

import re
print( re.sub(r"t([0-9])([0-9])", r"t\2\1", "t13 t19 t81 t25") )

# Output: 't31 t91 t18 t52'

OUTPUT: t31 t91 t18 t52

However, if you make a group ID like ’10’, this doesn’t work: \10 is read as ‘ID number 1 followed by 0’. So you have to be more specific and use the \g notation:

import re
print( re.sub(r"t([0-9])([0-9])", r"t\g<2>\g<1>", "t13 t19 t81 t25") )

# Output: 't31 t91 t18 t52'

OUTPUT: t31 t91 t18 t52

Using a replacement function

import re
items = ["zero", "one", "two"]
print( re.sub(r"a\[([0-3])\]", lambda match: items[int(match.group(1))], "Items: a[0], a[1], something, a[2]") )
       
# Output: 'Items: zero, one, something, two'

OUTPUT: Items: zero, one, something, two

ILLUSTRATION USING PYTHON3 CLI

Executed using python3 linux terminal

For the first part in using regular expressions and matching the string
you can visit this link โ€“>   ๐Ÿ‘‡ ๐Ÿ‘‡
Matching the beginning of a string (Regex) Regular Expressions in python

The re.search() method takes a regular expression pattern and a string and searches for that pattern within the string. If the search is successful, search() returns a match object or None otherwise.
For the second part in using regular expression and searching the string
visit โ€“> Searching โ€“ Regular Expressions (Regex) in Python

Precompiled_pattern โ€”> ๐Ÿ‘‡ ๐Ÿ‘‡
 Precompiled patterns โ€“ Regular Expression(Regex) in Python
Compiling a pattern allows it to be reused later on in a program.
However, note that Python caches recently-used expressions, so โ€œprograms that use only a few regular expressions at a time neednโ€™t worry about compiling regular expressionsโ€.

Flags in Regex ๐Ÿ‘‰ ๐Ÿ‘‰ Flags in Regular Expressions ( Regex ) in Pythonโ€ฆ.FTC
For some special cases we need to change the behavior of the Regular Expression, this is done using flags. Flags can be set in two ways, through the flags keyword or directly in the expression.