Python re
module handles regular expression.
search
method: return
>>> import re >>> x = "Perschon Python Online Tutorial" >>> m = re.search('Python',x) >>> if m: print("found") ...
found
match
method: return >>> m = re.match('Python',x) >>> if m: print("found")#No match >>> if m is None: print("no match") ...
no match
>>> m = re.match('Perschon',x) >>> if m is None: print("no match") ... >>> if m: print("found") ...
found
split
method: split string by pattern
>>> re.split('\s',x)
['Perschon', 'Python', 'Online', 'Tutorial']
>>> re.split('o',x)
['EndMem', ' Pyth', 'n Online Tut', 'rial']
findall
method: return all matches
>>> re.findall('o[a-z]',x)
['on', 'or']
sub
method: replace the match with pattern
>>> re.sub('o',"XXX", x)
'EndMemXXX PythXXX Online TutXXXial'Non greedy regular expression:
>>> x = "EndMemXXXXXXXXXXXXX PythXXXXXXn" >>> re.sub('X{6,13}','o',x)
'Perschon Python'
>>> x = "EndMemXXXXXXXXXXXXX PythXXXXXXn" >>> re.sub('X{6,13}?','o',x)
'PerschonoX Python'