Exploring python's re module

Posted by Afsal on 12-Apr-2024

Hi Pythonistas!

Regular expression, commonly known as regex, is a powerful way for searching, matching and manipulating strings. Python has a re module in the standard library for the same. It has many methods like search, match, compile etc. Most of us have doubts regarding which to use when. Today we are learning each method deeply with examples. Let’s get started

re.search

The re.search() method searches for the first occurrence of a pattern within a string. It returns a match object if the pattern is found, or None otherwise.

code

import re

match_object = re.search(r'world', 'hello world')
print(match_object)  

match_object = re.search(r'world', 'hello world hello world')
print(match_object)

match_object = re.search(r'world', 'hello universe')
print(match_object)

Output

<re.Match object; span=(6, 11), match='world'>

<re.Match object; span=(6, 11), match='world'>

None

re.match

The re.match() method attempts to match the pattern at the beginning of the string. It checks if the pattern matches at the start of the string and returns a match object if found; otherwise, it returns None.

code

match_object = re.match(r'hello', 'hello world')

print(match_object)

match_object = re.match(r'world', 'hello world')

print(match_object)

Output

<re.Match object; span=(0, 5), match='hello'>

None

re.fullmatch

The re.fullmatch() method checks if the entire string matches the given pattern. It returns a match object if the entire string matches the pattern; otherwise, it returns None.

code

match_object = re.fullmatch(r'hello', 'hello')

print(match_object)  

match_object = re.fullmatch(r'hello', 'hello world')

print(match_object) 

Output

<re.Match object; span=(0, 5), match='hello'>

None

I hope you learned something from this post, We will cover other methods in the upcoming post. Please share your valuable suggestions with afsal@parseltoungue.co.in