1. 程式人生 > >Python正則表示式Re中findall

Python正則表示式Re中findall

findall中()裡面的內容是需要捕獲的內容,但是如果我們想捕獲整個正則表示式的結果則需要新增如下程式碼:

#-*-coding:utf8-*-
import re
str1 = "[email protected]@[email protected]@asdfcom"
a=re.findall(r"\[email protected](qq|163|126)\.com",str1)
print(a)
b=re.findall(r"\[email protected](?: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