Regular expression is a set of characters, called as the pattern, which helps in finding substrings in a given string. The pattern is used to detect the substrings
For example, suppose you have a dataset of customer reviews about your restaurant. Say, you want to extract the emojis from the reviews because they are a good predictor of the sentiment of the review.
Take another example, the artificial assistants such as Siri, Google Now use information retrieval to give you better results. When you ask them for any query or ask them to search for something interesting on the screen, they look for common patterns such as emails, phone numbers, place names, date and time and so on. This is because then the assitant can automatically make a booking or ask you to call the resturant to make a booking.
Regular expressions are very powerful tool in text processing. It will help you to clean and handle your text in a much better way.
https://pycon2016.regex.training/cheat-sheet - Cheat Sheet
import re
Let's do a quick search using a pattern.
re.search('Ravi', 'Ravi is an exceptional student! Ravi is Brilliant')
<_sre.SRE_Match object; span=(0, 4), match='Ravi'>
# print output of re.search()
match = re.search('Ravi', 'Ravi is an exceptional student! Raviis brilliant')
print(match.group())# Finds only the first instance of a string
Ravi
### Get starting position of the word Ravi
print("Starting position of the word Ravi",match.start())
print("Ending position of the word Ravi",match.end())
Starting position of the word Ravi 0
Ending position of the word Ravi 4
Let's define a function to match regular expression patterns
def find_pattern(text, patterns,flags=None):
if flags=='I':
if re.search(patterns, text,flags=re.I):
return 'Found a match!'
else:
return 'Not Found!'
if re.search(patterns, text):
return 'Found a match!'
else:
return 'Not Found!'
# '*': Zero or more
print(find_pattern("ac", "ab*"))
print(find_pattern("abc", "ab*"))
print(find_pattern("abbc", "ab*"))
print(find_pattern("home--brew","home-*brew"))
print(find_pattern("home brew","home-*brew"))
print(find_pattern("abedbc", "ab*bc"))#abc, abbbbbc are all valid strings here
Found a match!
Found a match!
Found a match!
Found a match!
Not Found!
Not Found!
pattern='1010*'
print(find_pattern("10", pattern))
print(find_pattern("10100", pattern))
print(find_pattern("101000", pattern))
print(find_pattern("101", pattern))
print(find_pattern("100", pattern))
print(find_pattern("1", pattern))
Not Found!
Found a match!
Found a match!
Found a match!
Not Found!
Not Found!
pattern = '11*0' #can also be written as 1+0
print(find_pattern("11111110",pattern))
print(find_pattern("11",pattern))
Found a match!
Not Found!
# '?': Zero or one (tells whether a pattern is absent or present)
print(find_pattern("ac", "ab?"))
print(find_pattern("abc", "ab?"))
print(find_pattern("abbc", "ab?"))
print(find_pattern("home--brew","home-?brew")) # This matches either home-brew or homebrew
print(find_pattern("home brew","home-?brew"))
print(find_pattern("abedbc", "ab?bc"))
Found a match!
Found a match!
Found a match!
Not Found!
Not Found!
Not Found!
## Check if word car or cars is present in a string - cars?, says S can either be present or absent
print(find_pattern("I love my car","cars?"))
print(find_pattern("I love cars","cars?"))
print(find_pattern("I love cabs","cars?"))
Found a match!
Found a match!
Not Found!
xyz xy xz x
Make sure that the regular expression doesn’t match the following words: Xyyz Xyzz Xyy Xzz Yz
pattern='xy?z?'
print(find_pattern("Xyyz",pattern))
Not Found!
# '+': One or more
print(find_pattern("ac", "ab+"))
print(find_pattern("abc", "ab+"))
print(find_pattern("abbc", "ab+"))
Not Found!
Found a match!
Found a match!
pattern ='[1-9]*0+'
print(find_pattern("100",pattern))
print(find_pattern("20",pattern))
Found a match!
Found a match!
# {n}: Matches if a character is present exactly n number of times
print(find_pattern("abbc", "ab{2}"))
Found a match!
# {m,n}: Matches if a character is present from m to n number of times
print(find_pattern("aabbbbbbc", "ab{3,5}")) # return true if 'b' is present 3-5 times
print(find_pattern("aabbbbbbc", "ab{7,10}")) # return true if 'b' is present 7-10 times
print(find_pattern("aabbbbbbc", "ab{,10}")) # return true if 'b' is present atmost 10 times
print(find_pattern("aabbbbbbc", "ab{10,}")) # return true if 'b' is present from at least 10 times
Found a match!
Not Found!
Found a match!
Not Found!
pattern='hur{2,5}ay'
print(find_pattern("hurrrrray",pattern))
Found a match!
# '^': Indicates start of a string
# '$': Indicates end of string
print(find_pattern("James", "^J")) # return true if string starts with 'J'
print(find_pattern("Pramod", "^J")) # return true if string starts with 'J'
print(find_pattern("India", "a$")) # return true if string ends with 'a'
print(find_pattern("Japan", "a$")) # return true if string ends with 'a'
Found a match!
Not Found!
Found a match!
Not Found!
# '.': Matches any character
print(find_pattern("a", "."))
print(find_pattern("#", "."))
Found a match!
Found a match!
# Now we will look at '[' and ']'.
# They're used for specifying a character class, which is a set of characters that you wish to match.
# Characters can be listed individually as follows
print(find_pattern("a", "[abc]"))
# Or a range of characters can be indicated by giving two characters and separating them by a '-'.
print(find_pattern("c", "[a-c]")) # same as above
Found a match!
Found a match!
# '^' is used inside character set to indicate complementary set
print(find_pattern("a", "[^abc]")) # return true if neither of these is present - a,b or c
Not Found!
Pattern | Matches |
---|---|
[abc] | Matches either an a, b or c character |
[abcABC] | Matches either an a, A, b, B, c or C character |
[a-z] | Matches any characters between a and z, including a and z |
[A-Z] | Matches any characters between A and Z, including A and Z |
[a-zA-Z] | Matches any characters between a and z, including a and z ignoring cases of the characters |
[0-9] | Matches any character which is a number between 0 and 9 |
Pattern | Equivalent to |
---|---|
\s | [ \t\n\r\f\v] |
\S | [^ \t\n\r\f\v] |
\d | [0-9] |
\D | [^0-9] |
\w | [a-zA-Z0-9_] |
\W | [^a-zA-Z0-9_] |
print(find_pattern("aabbbbbb", "ab{3,5}")) # return if a is followed by b 3-5 times GREEDY
Found a match!
print(find_pattern("aabbbbbb", "ab{3,5}?")) # return if a is followed by b 3-5 times GREEDY
Found a match!
# Example of HTML code - this gives entire length of string. But, we want to match each html tag
print(re.search("<.*>","<HTML><TITLE>My Page</TITLE></HTML>"))
<_sre.SRE_Match object; span=(0, 35), match='<HTML><TITLE>My Page</TITLE></HTML>'>
# Example of HTML code
print(re.search("<.*?>","<HTML><TITLE>My Page</TITLE></HTML>"))
<_sre.SRE_Match object; span=(0, 6), match='<HTML>'>
match() Determine if the RE matches at the beginning of the string
search() Scan through a string, looking for any location where this RE matches
findall() Find all the substrings where the RE matches, and return them as a list
finditer() Find all substrings where RE matches and return them as asn iterator
sub() Find all substrings where the RE matches and substitute them with the given string
# - this function uses the re.match() and let's see how it differs from re.search()
def match_pattern(text, patterns):
if re.match(patterns, text):
return re.match(patterns, text)
else:
return ('Not found!')
print(find_pattern("abbc", "b+"))
Found a match!
print(match_pattern("abbc", "b+"))
Not found!
## Example usage of the sub() function. Replace Road with rd.
street = '21 Ramakrishna Road'
print(re.sub('Road', 'Rd', street))
21 Ramakrishna Rd
print(re.sub('R\w+', 'Rd', street))
21 Rd Rd
## Example usage of finditer(). Find all occurrences of word Festival in given sentence
text = 'Diwali is a festival of lights, Holi is a festival of colors!'
pattern = 'festival'
for match in re.finditer(pattern, text):
print('START -', match.start(), end="")
print('END -', match.end())
START - 12END - 20
START - 42END - 50
# Example usage of findall(). In the given URL find all dates
url = "http://www.telegraph.co.uk/formula-1/2017/10/28/mexican-grand-prix-2017-time-does-start-tv-channel-odds-lewisl/2017/05/12/"
date_regex = '/\d{4}/\d{1,2}/\d{1,2}/'
print(re.findall(date_regex, url))
['/2017/10/28/', '/2017/05/12/']
We use group() function. Grouping is achieved using the parenthesis operators. Grouping is a very useful technique when you want to extract substrings from an entire match.
## Exploring Groups
date_regex = '/(\d{4})/(\d{1,2})/(\d{1,2})/'
m1 = re.search(date_regex, url)
print(m1.group()) ## print the matched group
/2017/10/28/
print(m1.group(1)) # - Print first group
2017
print(m1.group(2)) # - Print second group
10
print(m1.group(3)) # - Print third group
28
print(m1.group(0)) # - Print zero or the default group
/2017/10/28/
pattern='(23){1,}(78){1,}'
print(find_pattern('2378',pattern))
print(find_pattern('235678',pattern))
print(find_pattern('237878',pattern))
Found a match!
Not Found!
Found a match!
Basketball Baseball Volleyball Softball Football
pattern='(Basket|Base|Volley|Soft|Foot){1,}ball'
print(find_pattern('Basketball',pattern))
print(find_pattern('Softball',pattern))
print(find_pattern('ball',pattern))
Found a match!
Found a match!
Not Found!
pattern='[a-z0-9]{1,}\*{1}[a-z0-9]{1,}'
print(find_pattern('3%4',pattern))
Not Found!
pattern='^A'
print(find_pattern('All',pattern))
print(find_pattern('all',pattern))
Found a match!
Not Found!
pattern='^A'
print(find_pattern('all',pattern,flags='I'))
Found a match!
pattern='(ing)$'
print(find_pattern('growing',pattern,flags='I'))
print(find_pattern('GrowIng',pattern,flags='I'))
print(find_pattern('Grow',pattern,flags='I'))
Found a match!
Found a match!
Not Found!
#11000011000111
pattern='^1{1,}0{3,}1*0{1,7}1{2,3}$'
print(find_pattern('1000011000111',pattern))
print(find_pattern('110000110001',pattern))
print(find_pattern('0000110001',pattern))
Found a match!
Not Found!
Not Found!
pattern='.{4}0{3}1{2}.{2}'
print(find_pattern('a00011as',pattern))
print(find_pattern('000000011as',pattern))
print(find_pattern('012300011as',pattern))
print(find_pattern('01ab00011as',pattern))
Not Found!
Found a match!
Found a match!
Found a match!
pattern='^[a-z]{3,15}$'
print(find_pattern('01ab00011as',pattern,flags='I'))
print(find_pattern('Balasubrahmanyam',pattern,flags='I'))
print(find_pattern('Aiswarya',pattern,flags='I'))
print(find_pattern('Aiswarya Ramachandran',pattern,flags='I'))
Not Found!
Not Found!
Found a match!
Not Found!
pattern='^[a-zA-Z]{1,10}\d{4}$'
print(find_pattern('sam2340',pattern))
print(find_pattern('irfann2590',pattern))
print(find_pattern('8730',pattern))
print(find_pattern('bobby8903834',pattern))
Found a match!
Found a match!
Not Found!
Not Found!
### Match only first tag - Non Greedy
pattern = "<.*?>"
string="<html> <head> <title> My amazing webpage </title> </head> <body> Welcome to my webpage! </body> </html>"
re.search(pattern,string)
<_sre.SRE_Match object; span=(0, 6), match='<html>'>
string = "0101"
pattern='(01+){2,}'
re.match(pattern,string)
<_sre.SRE_Match object; span=(0, 4), match='0101'>
“You can reach us at 07400029954 or 02261562153 ”
string="You can reach us at 07400029954 or 02261562153"
pattern="\d{11}"
replacement="####"
re.sub(pattern,replacement,string)
'You can reach us at #### or ####'
pattern="^[A-z]"
replacement="$"
string="Building careers of tomorrow"
re.sub(pattern,replacement,string)
'$uilding careers of tomorrow'
word_regex='\w*'
string='Do not compare apples with oranges. Compare apples with apples'
result=[]
for val in re.finditer(word_regex, string):
if(val.end() - val.start())>=5:
result.append(val.group())
print(result)
['compare', 'apples', 'oranges', 'Compare', 'apples', 'apples']
word_regex='(\w+ing)'
string="Playing outdoor games when its raining outside is always fun!"
result=re.findall(word_regex,string)
['Playing', 'raining']
string='Today’s date is 18-05-2018.'
date_regex='\d{2}-\d{2}-\d{4}'
m1 = re.search(date_regex, string)
m1.group()
'18-05-2018'
string='Today’s date is 18-05-2018.'
date_regex='(\d{2})-(\d{2})-(\d{4})'
m1 = re.search(date_regex, string)
m1.group(2)
'05'
string="user_name_123@gmail.com"
pattern="(\w+)@([A-z]+\.com)"
m1=re.search(pattern,string)
m1.group(2)
'gmail.com'