re regular expression instance code for python

  • 2020-07-21 09:03:58
  • OfStack

This paper focuses on the re regular expressions of python, as follows.

Concept: A regular expression (the general term formula) is an expression used to succinctly express a set of strings. The advantage is brevity. One line is worth a thousand words.

Application: String matching.

Example code:


CODEC = 'UTF-8' 
#encoding:utf-8 
import re 
 
p=re.compile("ab") 
str = "abfffa"  
#match Must match the initial letter  
if p.match(str): 
  print p.match(str).group()     
 
#match Must match the initial letter ,group() Print out the matching letters  
print re.match('a+b', 'abvvaabaaab').group() 
# and match To match letters in any position  
print re.search('a+b', 'vvvaabaaab').group() 
# Put all eligible letters to list It's all in the form of a set  
print re.findall('a+b','vabmaabnaaab') 
 
print re.split(':', 'str1:str2:str3') 
# Cannot match regular expression  
 
print ('str1:str2:str3').split(':') 
 
# In order to a+b Form to separate strings that can match regular expressions  
print re.split('a+b','vabmaabnaaab') 

The print information


ab 
ab 
aab 
['ab', 'aab', 'aaab'] 
['str1', 'str2', 'str3'] 
['str1', 'str2', 'str3'] 
 
['v', 'm', 'n', ''] 

conclusion


Related articles: