0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

re.groupとre.compileとre.VERBOSE

Last updated at Posted at 2020-07-14
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'))
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?