Python正则表达式Re中findall

findall中()里面的内容是需要捕获的内容,但是如果我们想捕获整个正则表达式的结果则需要添加如下代码:

#-*-coding:utf8-*-
import re
str1 = "[email protected]@[email protected]@asdfcom"
a=re.findall(r"\w+@(qq|163|126)\.com",str1)
print(a)
b=re.findall(r"\w+@(?:qq|163|126)\.com",str1)
print(b)
D:\Python27\python.exe D:/Users/liusen/PycharmProjects/ctrip_work/test_regex/test_re_findall.py
['qq', '163', '126']
['[email protected]', '[email protected]', '[email protected]']

Process finished with exit code 0

如果我们不想捕获()里面的内容,则需要如下:

#-*-coding:utf8-*-
import re
import codecs
rules=u"([1-9]\\d*\\.?\\d*|0\\.\\d*[1-9])(?=公里|千米|KM|km)"
pattern = re.compile(rules)
all_data=pattern.findall(u"上海南站2.5千米的酒店")
print("".join(list(all_data[0])))

实验结果如下:

D:\Python27\python.exe D:/Users/liusen/PycharmProjects/ctrip_work/test_regex/test_match.py
2.5

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/baidu_15113429/article/details/85679774
今日推荐