天天看点

python正则表达式正则表达式的应用

正则表达式的应用

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。