import re
How to create a regular expression object and then match
#Generate
cmpObj = re.compile(r'a.c')
#matching
ret = cmpObj.match('abc')
Matching is possible without creating a regular expression object. However, if you use the same regular expression pattern many times in your program, it is more efficient to create and use a regular expression object.
#matching
ret = re.match(r'a.c', 'abc')
If the string matches the regular expression pattern, the match object is returned as the return value of match ().
If there is no match, None will be returned.
Since match () checks whether the beginning of the string matches, it does not match in the following cases
#This does not match
ret = re.match(r'a.c', 'babc')
Use search () to check if there is a match not only at the beginning of the string but also in the middle.
#This matches
ret = re.search(r'a.c', 'babc')
#When using a regular expression object
ret = cmpObj.search('babc')
if ret :
print(ret) #If it matches
else :
print('not match') #If there is no match
str or bytes for the pattern and the search string, but you cannot mix str and bytes.\ as a special character)Recommended Posts