import re
s = ('arn:aws:cloudformation:us-east-2:123456789012:stack/'
'mystack-mynestedstack-sggfrhxhum7w'
'/f449b250-b969-11e0-a185-5081d0136786')
# [\w-]Means alphanumeric characters or hyphens
#I have a group name
m = re.match(r'arn:aws:cloudformation:(?P<region>[\w-]+):(?P<account_id>[\d]+)'
r':stack/(?P<stack_name>[\w-]+)/[\w-]+', s)
if m:
#Can be accessed by group name
print(m.group('region'))
print(m.group('account_id'))
print(m.group('stack_name'))
It's efficient when you write the regular expression part many times.
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:
#Can be accessed by group name
print(m.group('region'))
print(m.group('account_id'))
print(m.group('stack_name'))
I can write beautifully
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:
#Can be accessed by group name
print(m.group('region'))
print(m.group('account_id'))
print(m.group('stack_name'))