需求:在一个给定的字符串中拿出特定的字符串,或者检测一个给定的字符串是否满足特定要求
方案:使用正则表达式
1.re.finadll(parten,string)
在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。
注意: match 和 search 是匹配一次 findall 匹配所有。
str = "a23b\na34b"
re.findall(r"a(\d+)b.+a(\d+)b", str)
#输出[]
#因为不能处理str中间有\n换行的情况
#如果你要多行匹配,那么需要加上re.S和re.M标志
re.findall(r"a(\d+)b.+a(\d+)b", str, re.S)
#加上re.S后, .将会匹配换行符,默认.不会匹配换行符,s输出[('23', '34')]
re.findall(r"^a(\d+)b", str, re.M)
#输出['23', '34']
findall返回的是()里面的内容
在一些情况,需要对字符串先预处理,比如进行替换,变成方便使用正则的形式,然后再用正则。
parten1 = "listOptionValue builtIn=false value=(\w+)=(\w+)"
line = <listOptionValue builtIn="false" value="SYname=1000000"/>
line = line.replace("\"",'').replace('<',"").replace(">","").replace("/",'')
ss = re.findall(parten1,line)
print(ss)
#[('SYname', '1000000')]
也可先complie,再findall
pattern = re.compile(r'\d+') # 查找数字
result1 = pattern.findall('runoob 123 google 456')
result2 = pattern.findall('run88oob123google456', 0, 10)
#从位置0开始,10结束
print(result1)
print(result2)
输出结果:
['123', '456']
['88', '12']
- re.search方法
re.search 扫描整个字符串并返回第一个成功的匹配。
函数语法:
re.search(pattern, string, flags=0)
line = "Cats are smarter than dogs";
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
if searchObj:
print "searchObj.group() : ", searchObj.group()
print "searchObj.group(1) : ", searchObj.group(1)
print "searchObj.group(2) : ", searchObj.group(2)
else:
print "Nothing found!!"
以上实例执行结果如下:
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
re.match与re.search的区别
re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
line = "Cats are smarter than dogs";
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
print "match --> matchObj.group() : ", matchObj.group()
else:
print "No match!!"
matchObj = re.search( r'dogs', line, re.M|re.I)
if matchObj:
print "search --> searchObj.group() : ", matchObj.group()
else:
print "No match!!"
以上实例运行结果如下:
No match!!
search --> searchObj.group() : dogs
参考:https://www.runoob.com/python/python-reg-expressions.html