Showing posts with the label Regular Expression

Regular Expressions with Python: Look ahead and Look behind

These two important tools have been bugging me every time I come up with a situation. Because I never remember this one. Blame my memory.
So it's time I cement this idea somewhere . And no better place than a blog page.

LOOK AHEADLOOK AHEAD means , I want to see what lies ahead first, and then decide, to do something now.
Syntax of regex pattern:pattern1(?=pattern2)

Where Pattern1 is the pattern for the part that we ACTUALLY want to capture. Pattern2 is the pattern which needs to be found as MANDATORY. Logically speaking, 
IFPATTERN2isFOUND, then print/get/capture/show PATTERN1

Example: Let there be a string "Hello World"
Aim: I want to find 'Hello' ...ONLY IF its followed by 'World''\w+(?= World)', 'Hello World').group()
Result : >> 'Hello'
 The \w+ is Pattern1 The 'World' is Pattern2 r'\w+(?= World)' means, Find anything which fits \w+ IF it is followed by 'World'
The Pattern2 …

Regular Expressions with Python: Examples of common functions

Regular Expressions are tools to filter and grab information from a heap of strings. Python has got a lot of toys to deal with it. The module "re". I am going to give you a quick ride through it. The ones that we use/gonna use the most.

So just immediately launch your favourite IDE and type "import re". Let's get started.

for the object r where r =, subject), r.start() - Gives the start point where the match was found. r.end() - Gives the end point where the match was found. - Returns the full matched string - Returns the matched string for the 1st group - Returns the matched string for the 2nd group
And so on....

Note : is same as

The number of groups available depends on the number of groups used in your pattern.


>>>regex=r"([a-zA-Z]+) (\d+)">>>,'July 4')<_sre.SRE_Matchobjectat0x0000000002E4D140>>>>r=re.s…