正則表達式練習

在接口中使用正則一般分爲三步spa

 

第一步:先生成一個對象實例對象

好比 pattern = re.compile('hello') 這時就會生成一個去匹配'hello'字符串的對象接口

 

第二步:使用生成的對象去匹配文本字符串

好比:match = pattern.match('hello word')  匹配成功返回匹配到的對象,匹配失敗返回Nonestring

match是匹配開頭,若是開頭不匹配,直接返回None 若是想要匹配全部的字符串,能夠使用search,都是匹配一個,danshisearch能夠全局匹配it

re.search(r'\d+','hhs12kak2233jjj').group()  只能夠匹配到一個符合條件的字符串class

 

第三步 使用match.group()將匹配到的字符串分組出來 分組以前先判斷匹配到的值是否返回的是None方法

好比:match.group()word

 

經常使用的一些re方法co

re.split  將匹配到符合條件的字段刪除

re.split(r'hello','hell word jjj hello')

得出結果:['', ' word hah ', '']

 

re.findall  匹配到全部符合條件的字段,列表形式返回

re.findall('r'hello','hell word jjj hello'')

得出結果:['hello', 'hello']

 

re.sub 將匹配到的字符串替換掉

re.sub(r'\s+','-',s)  第一個是匹配的規則,第二個是須要替換成的新字符,第三個是字符串

 

re.subn  會返回替換的次數

 

用正則去匹配一個郵箱

re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$',text)

相關文章
相關標籤/搜索