import re
s = ('arn:aws:cloudformation:us-east-2:123456789012:stack/'
'mystack-mynestedstack-sggfrhxhum7w'
'/f449b250-b969-11e0-a185-5081d0136786')
# [\w-]で英数字もしくはハイフンの意味になる
# group名をつけています
m = re.match(r'arn:aws:cloudformation:(?P<region>[\w-]+):(?P<account_id>[\d]+)'
r':stack/(?P<stack_name>[\w-]+)/[\w-]+', s)
if m:
# group名でアクセスできます
print(m.group('region'))
print(m.group('account_id'))
print(m.group('stack_name'))
#re.compileを使う場合
正規表現の部分を何度も書く場合に、効率的です。
import re
s = ('arn:aws:cloudformation:us-east-2:123456789012:stack/'
'mystack-mynestedstack-sggfrhxhum7w'
'/f449b250-b969-11e0-a185-5081d0136786')
RE_STACK_ID = re.compile(r'arn:aws:cloudformation:(?P<region>[\w-]+):(?P<account_id>[\d]+)'
r':stack/(?P<stack_name>[\w-]+)/[\w-]+')
m = RE_STACK_ID.match(s)
if m:
# group名でアクセスできます
print(m.group('region'))
print(m.group('account_id'))
print(m.group('stack_name'))
#更に、re.VERBOSEを場合
きれいに書けます
import re
s = ('arn:aws:cloudformation:us-east-2:123456789012:stack/'
'mystack-mynestedstack-sggfrhxhum7w'
'/f449b250-b969-11e0-a185-5081d0136786')
RE_STACK_ID = re.compile(r"""
arn:aws:cloudformation:
(?P<region>[\w-]+): #region
(?P<account_id>[\d]+): #account_id
stack/
(?P<stack_name>[\w-]+)/ #stack_name
[\w-]+""", re.VERBOSE)
m = RE_STACK_ID.match(s)
if m:
# group名でアクセスできます
print(m.group('region'))
print(m.group('account_id'))
print(m.group('stack_name'))