Page 1 of 1

Regex

Posted: Wed May 29, 2024 12:47 pm
by admin
#Regex Simple Match (REG01) – Search

Code: Select all

# Check if a string contains the word 'apple'
import re

text = "I love apples and bananas."
pattern = re.compile(r'\bapple\b')
result = pattern.search(text)

if result:
    print("Match found!")
else:
    print("No match.")
#Regex extract Email - (REG02)

Code: Select all

# Extract email addresses from a string
import re

text = "Contact us at john.doe@icai.org or jane.smith@sirc.com for assistance."
pattern = re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b')
matches = pattern.findall(text)

print("Email Addresses:", matches)

#Regex Split REG03

Code: Select all

#Regex Split REG03
import re

# Split a string into words using whitespace as the delimiter
text = "This is a simple sentence."
words = re.split(r'\s', text)

print("Words:", words)
#Regex Date Split REG04

Code: Select all

#Regex Date Split
import re

# Extract date components (day, month, year) from a date string
date_string = "Today is 2022-01-23."
pattern = re.compile(r'(\d{4})-(\d{2})-(\d{2})')
match = pattern.search(date_string)

if match:
    year, month, day = match.groups()
    print("Year:", year)
    print("Month:", month)
    print("Day:", day)