(6) Develop programs to learn Regular Expressions using python.
1) match() function 2) search() function
3) compile() function 4) findall() function
5) split() function
Program Code-1:match() & search() method
#Lab-6. Develop programs to learn regular expressions(re) using python.
# A Program by USING re.match() method:
""
#import re #simple structure of re.match()
#matchObject = re.match(pattern, input_str, flags=0)
""
#!/usr/bin/python
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
print ("matchObj.group() : ", matchObj.group())
print ("matchObj.group(1) : ", matchObj.group(1))
print ("matchObj.group(2) : ", matchObj.group(2))
else:
print ("No match!!")
import re
pattern = '^ba...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search is successful.")
else:
print("Search is unsuccessful.")
#The search() function searches the string for a match, and
#returns a Match object if there is a match.import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
import re
txt = "The rain in Spain"
x = re.search("ai", txt)
print(x) #this will print an object
Output-1: match() & search() method
Program Code-2:compile() & findall() method
#Lab-6. Develop programs to learn regular expressions using python.
# A Program by USING re.compile() & re.findall() method:
import re
# compile() creates regular expression character class [a-e],
# which is equivalent to [abcde].
# class [abcde] will match with string with 'a', 'b', 'c', 'd', 'e'.
p = re.compile('[a-e]')
# findall() searches for the Regular Expression and return a list upon finding
print(p.findall("Hello my college is in surat gtu aicte"))
Program Code-3:compile() & findall() method
#Lab-6. Develop programs to learn regular expressions using python.
# A Program by USING re.compile() & re.findall() method:
import re
# \d is equivalent to [0-9].
p = re.compile('\d')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
# \d+ will match a group on [0-9], group of one or greater size
p = re.compile('\d+')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
No comments:
Post a Comment