Basics of Regular Expressions in Python, check the link below ๐ ๐
Also with table of contents about symbols and their usage in Regex
Regular Expressions Regex basic in Python ๐ ๐
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
![](http://www.fcukthecode.com/wp-content/uploads/2022/02/Screenshot-from-2022-02-08-10-02-25.png)
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.