Account
Categories

Re Module (Regular Expressions)


Definition:

It is a module that works with text or data to find patterns.

It searches and extracts specific data, such as numbers, words, or patterns, from text or files.

It helps to match and find the required information from a given dataset.

Now you will clearly understand the code logic with the help of the flowchart.

Re Module Flowchart :

Start
↓
You write the program and import the re module
import re
↓
You create the text in the program
text = "My number is 54321"
↓
You give the pattern in the re module
\d+ (to find numbers)
↓
re module searches the pattern in the text
↓
Match found?
↓
Yes 
↓
Extract data → result.group()
↓
Print output → 54321
↓
End

Syntax:


import re

Example:


import re

text = "My number is 54321"
result = re.search(r'\d+', text)

print(result.group())

Output:

Exercise

Use re module to extract numbers from a given text in Python.