pattern refers to a regular expression pattern string refers to group of characters flags refers to control flags that re module uses to customize its processingre.search(pattern, string, flag)search method looks for the first match of the pattern in the string and return a group object.group object has a span field that contains the beginning and the end indices of the found substring. And its match field contains the found substring import re # import re module to handle regular expressions
pattern = "Ali"
string = "My name is Ali"
print( re.search(pattern, string))
re.match(pattern, string, flag)match method is similar to the search method except that it matches the pattern only to the beginning of the string. pattern = "Ali"
string = "My name is Ali"
print( re.match(pattern, string))
string = "Ali is my name"
print( re.match(pattern, string))
search and match methods return an group object that contains the found substring or None. Therefore, we can test the returned value before processing it.pattern = "Ali"
string = "My name is Noor"
groupObj = re.search(pattern, string)
print(bool(groupObj))
pattern = "Noor"
groupObj = re.search(pattern, string)
print(bool(groupObj))
group object invoke the group() method on the returned object. pattern = "Noor"
string = "My name is Noor"
groupObj = re.search(pattern, string)
if groupObj:
print(groupObj.group())
group object invoke start() (end()) method. pattern = "Noor"
string = "My name is Noor"
groupObj = re.search(pattern, string)
if groupObj:
print(groupObj.start())
re.findall(patter, string, flag)findall returns a list of strings that match the pattern in the stringpattern = 'Mohammed|Ali' # regular expression to look for the word Mohammed or Ali
string = "Mohammed is my name. Mohammed Ali is my full name"
print( re.findall(pattern, string))
search, match, and findall search on a substring levelre.I is set.print(re.search('a', 'ali').group())
groupObj = re.search('a', 'Ali');
if groupObj:
print('`a` is in `Ali`')
else:
print('`a` is NOT in `Ali`')
groupObj = re.search('a', 'Ali', re.I)
if groupObj:
print('`re.I` ignores letter case. So `a` is in `Ali`')
p = re.compile("x*")
p.sub('XY', 'xxx xx x')