[PYTHON] re.group, re.compile and re.VERBOSE

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'))

When using re.compile

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'))

Furthermore, in the case of re.VERBOSE

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'))

Recommended Posts

re.group, re.compile and re.VERBOSE
re.split and re.compile
Splitting re.split and replacing re.compile