正規表達式的應用
re.compile 想要把每個比對的字元列印出來,須使用(?P<name>)元字元和group函數;
(?P<name>)的元字元何以在後面通過<name>引用,例:
pattern=re.compile(r'?P<match_word>The',re.I)
建立了一個組名為match_word的關于the的模式,不區分大小寫。
于是:
for word in string _list:
if pattern.search(word):
print("{:s}".format(pattern.search(word).group('match_word')))
如果單詞與模式比對,則傳回search傳回的資料結構。
替代結構:
pattern=re.compile(string_to_find,re.I)
print("Output #40:".format(pattern.sub("a",string)))
re.sub函數被用來替換string中的字段the。