LoginSignup
4
5

More than 5 years have passed since last update.

pythonの正規表現というか、マッチオブジェクトのメモ

Last updated at Posted at 2017-09-17

参考

6.2. re — 正規表現操作 — Python 3.6.1 ドキュメント

>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)       # The entire match
'Isaac Newton'
>>> m.group(1)       # The first parenthesized subgroup.
'Isaac'
>>> m.group(2)       # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2)    # Multiple arguments give us a tuple.
('Isaac', 'Newton')

シンボリックグループ(名前付きグループ, 名前付きキャプチャ)

6.2. re — 正規表現操作 — Python 3.6.1 ドキュメント

グループ “quote” を参照するコンテキスト 参照方法
同一パターンへの参照 (?P=quote)(そのまま)
\1
マッチオブジェクト m の処理時 m.group('quote')
m.end('quote')(etc.)
re.sub() の repl 引数へ渡される文字列 \g<quote>
\g<1>
\1

match.group(), match.groupdict()の挙動

挙動を調べるサンプル

example.txt
 .text            000c4342+000000f0 _ccc

000c4342+000000f0にマッチさせるように、正規表現("(?P<addr>[0-9A-Fa-f]{8})\+(?P<size>[0-9A-Fa-f]{8})")を使うと、

In [217]: with open("example.txt") as f:
     ...:     for s in f:
     ...:         m = re.search("(?P<addr>[0-9A-Fa-f]{8})\+(?P<size>[0-9A-Fa-f]{8})",s)
     ...:         if m:
     ...:             print("m.groups()        : " + str(m.groups()))
     ...:             print("m.group()         : " + str(m.group()))
     ...:             print("m.group(0)        : " + str(m.group(0)))
     ...:             print("m.group(1)        : " + str(m.group(1)))
     ...:             print("m.group(2)        : " + str(m.group(2)))
     ...:             print("m.groupdict()     : " + str(m.groupdict()))
     ...:             print("m.group(\"addr\")   : " + str(m.group("addr")))
     ...:             print("m.group(\"size\")   : " + str(m.group("size")))
     ...:
     ...:
m.groups()        : ('000c4342', '000000f0')
m.group()         : 000c4342+000000f0
m.group(0)        : 000c4342+000000f0
m.group(1)        : 000c4342
m.group(2)        : 000000f0
m.groupdict()     : {'addr': '000c4342', 'size': '000000f0'}
m.group("addr")   : 000c4342
m.group("size")   : 000000f0
4
5
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
4
5