Python Reg Expressions

In this Python tutorial, let us know about Python Reg Expressions with suitable examples.

Introduction of Python Reg Expressions

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

RegEx Module

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

To Import the re module, use

import re

RegEx in Python

When we have imported the re module, we can start using regular expressions in Python as follows,

Example

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

Output

YES! We have a match!

RegEx Functions

The re module gives a set of functions that enables us to seek a string for a match.

  • findall – it returns a list containing all matches
  • search – it returns a Match object if there is a match anywhere in the string
  • split – it returns a list where the string has been split at each match
  • sub – it replaces one or many matches with a string

The findall() Function

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

Example for findall()

import re
str = "The rain in Spain"
x = re.findall("ai", str)
print(x)

Output

['ai', 'ai']

The search() Function

The search() function searches the string for a match.

Example for search()

import re
str = "The rain in Spain"
x = re.search("\s", str)
print("The first white-space character is located in position:", x.start())

Output

The first white-space character is located in position: 3

The split() Function

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

Example for split()

import re
str = "The rain in Spain"
x = re.split("\s", str)
print(x)

Output

['The', 'rain', 'in', 'Spain']

Leave a Comment

Your email address will not be published. Required fields are marked *