「Python開発」reモジュールMatch Objectオブジェクトの利用方法

1.group([group1,…])
例:
>>> m=re.match(“(\w+) (\w+)”,”abcd efgh, chaj”)
>>> m.group()
‘abcd efgh’
>>> m.group(1)#
‘abcd’
>>> m.group(2)
‘efgh’
>>> m.group(1,2) #
(‘abcd’, ‘efgh’)
>>> m=re.match(“(?P<first_name>\w+) (?P<last_name>\w+)”,”sam lee”)
>>> m.group(“first_name”)
‘sam’
>>> m.group(“last_name”)
‘lee’

2.groups([default])
例:
>>> m=re.match(“(\d+)\.(\d+)”,”23.123″)
>>> m.groups()
(’23’, ‘123’)
>>> m=re.match(“(\d+)\.?(\d+)?”,”24″) #デフォルト”None”
>>> m.groups()
(’24’, None)
>>> m.groups(“0”)
(’24’, ‘0’)

3.groupdict([default])
例:
>>> m=re.match(“(\w+) (\w+)”,”hello world”)
>>> m.groupdict()
{}
>>> m=re.match(“(?P<first>\w+) (?P<secode>\w+)”,”hello world”)
>>> m.groupdict()
{‘secode’: ‘world’, ‘first’: ‘hello’}

4.split
例1:
>>> re.split(‘(\W+)’, ‘…words, words…’)
[”, ‘…’, ‘words’, ‘, ‘, ‘words’, ‘…’, ”]
>>> re.split(‘(\W+)’, ‘words, words…’)
[‘words’, ‘, ‘, ‘words’, ‘…’, ”]

例2:
>>> re.split(“\W+”,”words,words,works”,1)
[‘words’, ‘words,works’]
>>> re.split(“[a-z]”,”0A3b9z”,re.IGNORECASE)
[‘0A3’, ‘9’, ”]
>>> re.split(“[a-z]+”,”0A3b9z”,re.IGNORECASE)
[‘0A3’, ‘9’, ”]
>>> re.split(“[a-zA-Z]+”,”0A3b9z”)
[‘0’, ‘3’, ‘9’, ”]
>>> re.split(‘[a-f]+’, ‘0a3B9’, re.IGNORECASE)#re.IGNORECASEを利用
[‘0’, ‘3B9’]

5.re.findall(pattern, string[, flags])
例:
>>> re.findall(‘(\W+)’, ‘words, words…’)
[‘, ‘, ‘…’]
>>> re.findall(‘(\W+)d’, ‘words, words…d’)
[‘…’]
>>> re.findall(‘(\W+)d’, ‘…dwords, words…d’)
[‘…’, ‘…’]

6.subとsubn
例:
>>> re.sub(“\d”,”abc1def2hijk”,”RE”)
‘RE’
>>> x=re.sub(“\d”,”abc1def2hijk”,”RE”)
>>> x
‘RE’
>>> re.sub(“\d”,”RE”,”abc1def2hijk”,)
‘abcREdefREhijk’

>>> re.subn(“\d”,”RE”,”abc1def2hijk”,)
(‘abcREdefREhijk’, 2)