Exploring python's re module - part 2

Posted by Afsal on 19-Apr-2024

Hi Pythonistas!

This is part 2 of re module. In this post we will learn other methods. Let us jump into the code.

re.findall

This will return a list of matches.

code

import re

matches = re.findall(r'hello', 'hello world hello')

print(matches)

Output

['hello', 'hello']

re.finditer

This will return the an iterator 

code

matches_iterator = re.finditer(r'hello', 'hello world hello')

print(matches_iterator)

for match_object in matches_iterator:

    print(match_object.group())

output

<callable_iterator object at 0x716e40b67fd0>

hello

hello

re.sub

This method is used to substitute a pattern with another.

Code

import re

new_string = re.sub(r'hello', 'hi', 'hello world hello')

print(new_string)

Output

hi world hi

re.compile

The re.compile() function is used to compile a regular expression pattern into a regex object, which can then be used for various matching operations. This approach is beneficial when you intend to reuse the same pattern multiple times, as compiling it once can improve performance.

Code

import re

pattern = re.compile(r'hello')

match_object = pattern.search('hello world')

print(match_object.group())

Output

hello


I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in . In the upcoming post we will learn how to write regex pattern