正規表現パターンを re.compile() で作成する。作成したパターンオブジェクトで、正規表現処理を行う
>>> import re
>>> verb ='If change is happening on the outside faster than on the inside,
the end is in sight. -Jack Welch-'
>>> pattern = re.compile('[a-z]*side')
正規表現パターンが含まれるかどうかを検証する (含まれる場合には Object が返る。無い場合には None が返る)
>>> verb
'If change is happening on the outside faster than on the inside, the end is in sight.
-Jack Welch-'
>>> pattern = re.compile('[a-z]*side')
>>> pattern.search(verb)
<_sre.SRE_Match object at 0x024E6090>
>>> pattern2 = re.compile('f[uU]ck')
>>> pattern2.search(verb) is None
True
マッチする語を取り出したいときは findall
>>> pattern.findall(verb) ['outside', 'inside']
正規表現パターンに完全一致するかどうかを検証する (含まれる場合には Object が返る。無い場合には None が返る)
>>> verb
'If change is happening on the outside faster than on the inside, the end is in sight.
-Jack Welch-'
>>> pattern = re.compile('[a-z]*side')
>>> pattern.match(verb) is None
True
>>> pattern3 =re.compile('If.*-Jack Welch-')
>>> pattern3.match(verb)
<_sre.SRE_Match object at 0x024E6090>
置換
>>> verb
'If change is happening on the outside faster than on the inside, the end is in sight.
-Jack Welch-'
>>> pattern = re.compile('[a-z]*side')
>>> pattern.sub('[ ]', verb)
'If change is happening on the [ ] faster than on the [ ], the end
is in sight. -Jack Welch-'
>>> poem='しんしゅうしなののしんそばよりもわたしゃあなたのそばがいい'
>>> ptn=re.compile('しんそば')
>>> ptn.sub('新蕎麦', poem)
'しんしゅうしなのの新蕎麦よりもわたしゃあなたのそばがいい'
>>> ptn=re.compile('しん.*ば')
>>> ptn.sub('新蕎麦',poem)
'新蕎麦がいい'
さいごのは、"しんしゅうしなののしんそばよりもわたしゃあなたのそば" → "新蕎麦"