Python RegEx

Python RegEx (Regular Expressions)

A Regular Expression (RegEx) is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern.

Python has a built-in package called re, which can be used to work with Regular Expressions.


1. Import the re Module

To use regular expressions, you must first import the re module:

import re

2. RegEx Functions

The re module offers a set of functions that allows us to search a string for a match:

re.search()

The search() function searches the string for a match, and returns a Match object if there is a match.

search() Example

import re

txt = "The rain in Spain" x = re.search("^The.*Spain$", txt)

if x: print("YES! We have a match!") else: print("No match")

re.findall()

The findall() function returns a list containing all matches.

findall() Example

import re

txt = "The rain in Spain" x = re.findall("ai", txt)

print(x) // Output: ['ai', 'ai']

re.split()

The split() function returns a list where the string has been split at each match.

re.sub()

The sub() function replaces the matches with the text of your choice.

sub() Example

import re

txt = "The rain in Spain" x = re.sub("\s", "9", txt)

print(x) // The9rain9in9Spain


Metacharacters

Metacharacters are characters with a special meaning. Here are a few essential ones: