3.Python正则表达式

正则表达式与模糊匹配

#python包含了re 模块,它提供了在文本中搜索特定模式的强大功能。

#!/usr/bin/env python3 
from math import exp,log,sqrt 
import re 

string="The quick brown for jumps over the lazy dog."
string_list=string.split()   #拆分成列表。
pattern=re.compile(r"The",re.I) #编译正则表达式,可以提升运行效率。不是必须。
count=0 
for word in string_list:
	if pattern.search(word):
		count+=1 
print("{0:d}".format(count))
#re.compile 将文本形式的模式编译成为编译后的正则表达式。
#re.I不区分大小写。
#r可以确保Python不处理字符串中的转义字符(\,\t,\n)。
#不区分大小写搜索THE的个数。


from math import exp,log,sqrt
import re
string="The quick brown fox jumps over the lazy dog."
string_to_find=r"The"
pattern=re.compile(string_to_find,re.I) #忽略大小写编译字符串。
print("{:s}".format(pattern.sub("a",string))) #将the替换成a;
#a quick brown fox jumps over a lazy dog.
#re.sub 函数在string中寻找模式,然后将之替换为a;