How to Find, Search and Split the Strings in the File Using Regular Expressions in Python?
Share
Condition for Bank Operation Program Using Python Class and Member Functions
Description:
Regular expressions (regex) allow you to search, find, and manipulate text based on patterns.
Regular expressions are used to search for patterns in strings, such as finding specific words or
characters, splitting strings, or replacing text.
Step-by-Step Process
Import re module:
Python provides the re module for working with regular expressions.
Use re.search():
To find a specific pattern in the string.
Use re.findall():
To find all occurrences of a pattern in the string.
Use re.split():
To split the string based on a pattern.
Process with a File:
To search and manipulate text inside a file, read the file and apply regular expressions on its contents.
Sample Code
import re
import csv
file_path = '/home/soft23/Downloads/DATASETS/sample2.csv'
with open(file_path, 'r') as file:
csv_reader = csv.reader(file)
content = list(csv_reader)
csv_content = '\n'.join([','.join(row) for row in content])
pattern = r'Python'
match = re.search(pattern, csv_content)
if match:
print("Found:", match.group())
else:
print("Pattern not found")
all_matches = re.findall(r'\bP\w*\b', csv_content)
print("Words starting with 'P':", all_matches)
split_content = [re.split(r',\s*', row) for row in csv_content.split('\n')]
print("Split content (rows and columns):", split_content)