Why regular Expressions are so powerful?

Niraj
1 min readJun 18, 2020

Regular expression is a sequence of characters that matches the search patterns.

Capturing groups

Portions of the patterns that are enclosed in parenthesis.

Let’s say that we have a list of people’s full names.These names are stored as last name, comma, first name.We want to turn this around and create a string that starts with the first name followed by the last name.

import re
def rearrange_name(name):
…. result = re.search(r’^([\w \.-]*), ([\w \.-]*)$’,name)
….if result is None:
……..return name
….return “{} {}”.format(result[2],result[1])
>>>rearrange_name(‘Poudel, Niraj’)
Niraj poudel
>>>rearrange_name(‘Kohli, Virat’)
Virat Kholi
>>>rearrange_name(‘Dhoni, Mahendra S.’)
Mahendra S. Dhoni

Converting a date of yyyy-mm-dd format to dd-mm-yyyy format using regular expression in python.

import re
def change_date_format(dt):
….return re.sub(r’(\d{4})-(\d{1,2})-(\d{1,2})’, ‘\\3-\\2-\\1’, dt)
dt1 = “1999–10–02”

print(“Original date in YYY-MM-DD Format: “,dt1)
Original date in YYY-MM-DD Format: 1999–10–02

print(“New date in DD-MM-YYYY Format: “,change_date_format(dt1))
New date in DD-MM-YYYY Format: 02–10–1999

Extracting a PID Using regexes in Python

import re
log = ‘December 01 05:21:40 my computer bad_process[12345]: Error performing package upgrade’
def extract_pid(log_line):
….regex = r”\[(\d+)\]”
….result = re.search(regex,log_line)
….if result is None:
……..return ‘’
….return result[1]

print(extract_pid(log))
>>>12345

--

--

Niraj

Sometimes you win sometimes you lose. So don't let the fear take over.