概要
Pythonで「マッチオブジェクトからマッチした文字列の情報を取得する(Match)」の動作を確認してみました。
以下のページを参考にしました。
実装
以下のファイルを作成しました。
sample.py
import re
msg = 'My birthday is 1998/09/25'
pattern = re.compile(r'\d{4}/\d{2}/\d{2}')
result = pattern.search(msg)
if result :
print('Match:' + result.group(0))
import re
msg = 'My birthday is 1998/09/25'
pattern = re.compile(r'(\d{4})/(\d{2})/(\d{2})')
result = pattern.search(msg)
if result :
print('Match:' + result.group(0))
print('Group1:' + result.group(1))
print('Group2:' + result.group(2))
print('Group3:' + result.group(3))
import re
msg = 'My birthday is 1998/09/25'
pattern = re.compile(r'(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})')
result = pattern.search(msg)
if result :
print('Match:' + result.group(0))
print('Group[year]:' + result.group('year'))
print('Group[month]:' + result.group('month'))
print('Group[day]:' + result.group('day'))
import re
msg = 'My birthday is 1998/09/25'
pattern = re.compile(r'(\d{4})/(\d{2})/(\d{2})')
result = pattern.search(msg)
if result :
print(result.group(1, 2, 3))
import re
msg = 'My birthday is 1998/09/25'
pattern = re.compile(r'\d{4}/\d{2}/\d{2}')
result = pattern.search(msg)
if result :
print('Match:' + result.group(0))
print('StartIndex:' + str(result.start(0)))
print('EndIndex:' + str(result.end(0)))
import re
msg = 'My birthday is 1998/09/25'
pattern = re.compile(r'(\d{4})/(\d{2})/(\d{2})')
result = pattern.search(msg)
if result :
print('Group1:' + result.group(1))
print('StartIndex:' + str(result.start(1)))
print('EndIndex:' + str(result.end(1)))
import re
msg = 'My birthday is 1998/09/25'
pattern = re.compile(r'(\d{4})/(\d{2})/(\d{2})')
result = pattern.search(msg)
if result :
for i in range(result.lastindex):
print('Group:' + str(i + 1) + ' ' + result.group(i + 1))
以下のコマンドを実行しました。
$ python3 sample.py
Match:1998/09/25
Match:1998/09/25
Group1:1998
Group2:09
Group3:25
Match:1998/09/25
Group[year]:1998
Group[month]:09
Group[day]:25
('1998', '09', '25')
Match:1998/09/25
StartIndex:15
EndIndex:25
Group1:1998
StartIndex:15
EndIndex:19
Group:1 1998
Group:2 09
Group:3 25
まとめ
何かの役に立てばと。