天天看點

re庫主要功能函數

#coding=utf-8
import re


#re.search(pattern, string, flags)比對正規表達式的第一個位置,傳回match對象
match = re.search(r'[1-9]\d{5}', 'BIT 100081')
if match:
    print match.group(0)


#re.match(pattern, string, flags)從字元串的開始位置比對正規表達式,傳回match對象
#不調整參數時會報錯
#match = re.match(r'[1-9]\d{5}', 'BIT 100081')
#調整參數
match = re.match(r'[1-9]\d{5}', '100081BIT')
if match:
    print match.group(0)
#報錯
# print match.group(0)
# Traceback (most recent call last):
#   File "C:/Users/Administrator/PythonWorkSpace/python14.py", line 10, in <module>
#     print match.group(0)
# AttributeError100081
# : 'NoneType' object has no attribute 'group'


#re.findall(pattern, string, flags)以清單類型傳回全部能比對的子串
ls = re.findall(r'[1-9]\d{5}', 'BIT100081 TSU100084')
print ls


#re.split(pattern, string, maxsplit, flags)将字元串按照正規表達式比對結果進行分割,傳回清單類型
#maxsplit:最大分割數
ls = re.split(r'[1-9]\d{5}', 'BIT100081 TSU100084')
print ls
ls = re.split(r'[1-9]\d{5}', 'BIT100081 TSU100084', 1)
print ls #隻比對第一個


#re.finditer(pattern, string, flags)傳回一個比對結果的疊代類型,每個疊代元素都是match對象
for m in re.finditer(r'[1-9]\d{5}', 'BIT100081 TSU100084'):
    if m:
        print m.group(0)


#re.sub(pattern, repl, string,count=0, flags=0)在一個字元串中替換所有比對正規表達式的子串,傳回替換後的字元串
#repl:替換比對字元串的字元串
#count:比對的最大替換次數
print re.sub(r'[1-9]\d{5}', ':zipcode', 'BIT100081 TSU100084')
print re.sub(r'[1-9]\d{5}', ':zipcode', 'BIT100081 TSU100084', 1)      

繼續閱讀