[RegEx][Python]使用正規運算式匹配一筆、多筆match範例
正規運算式匹配單筆的範例:
import re
html = 'abcd{111:333,444:555}cdefg'
pattern = r'.*?\{(?P<value>.*?)\}.*?'
# DOTALL:就是csharp裡面的singleline
pattern = re.compile(pattern, re.DOTALL)
# 取得匹配結果,無法匹配返回 None
match = pattern.match(html)
if match:
# 得到匹配結果
print(match.group('value'))
正規運算式匹配多筆的範例:
html = "<p>旅行名稱:去韓國玩,價錢:5,000,日期:2018/03/20</p><p>旅行名稱:去日本玩,價錢:8,000,日期:2018/07/15</p>"
pattern = r'旅行名稱:(?P<TourName>.*?),價錢:(?P<Price>[\d,]+),日期:(?P<Date>\d{4}/\d{2}/\d{2})</p>'
import re
# DOTALL:就是csharp裡面的singleline
pattern = re.compile(pattern, re.DOTALL)
for m in pattern.finditer(html):
print(m.group('TourName'))
print(m.group('Price'))
print(m.group('Date'))
print('program end')
快速測試上述範例的網址:
https://regex101.com/r/E3jFCm/1
參考資料:
[Python] 正規表示法 Regular Expression
http://zwindr.blogspot.com/2016/01/python-regular-expression.html
re.findall which returns a dict of named capturing groups?
https://stackoverflow.com/questions/11103856/re-findall-which-returns-a-dict-of-named-capturing-groups
Capturing named groups in regex with re.findall
https://stackoverflow.com/questions/25628973/capturing-named-groups-in-regex-with-re-findall