<!-Link-> [1]:https://docs.python.jp/3/library/re.html#match-objects
[6.2. Re — Regular Expression Manipulation — Python 3.6.1 Documentation] [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 — Regular Expression Manipulation — Python 3.6.1 Documentation] [1]
|Context to reference group “quote”|Reference method| |:---|:---| |Reference to the same pattern|・
(?P=quote)
(As it is)
・\1
| |Match objectm
At the time of processing|・m.group('quote')
・m.end('quote')
(etc.)| |re.sub()String passed to the repl argument of|・\g<quote>
・\g<1>
・\1
|
match.group ()
, match.groupdict ()
Sample to examine the behavior
example.txt
.text 000c4342+000000f0 _ccc
Regular expression ("(? P <addr> [0-9A-Fa-f] {8}) \ + (? P <size> [0-9A-Fa-] to match
000c4342 + 000000f0 If you use 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
Recommended Posts