リンク
ちゃんと調べるときは
http://www.python.jp/doc/release/
Wiki内検索
最近更新したページ
最新コメント
文字コードの判定 by awesome things!
正規表現 by awesome things!
辞書 by stunning seo guys
文字列の16進変換 by check it out
文字コードの変換 by check this out
デバッガ by check this out
サブプロセス by watch for this
文字コードの判定 by watch for this
サニタイジング by check this out
タグ

正規表現

詳しくはこっち

お約束
>>> import re

どうも tr/a-z/A-Z/ みたいなのは存在しないっぽい。

マッチング


>>> if re.compile("cde").search("abcdef"):
...   print "Match"
...
Match
>>> if re.compile("cde").match("abcdef"):
...   print "Match"
...
>>> if re.compile("abc").match("abcdef"):
...   print "Match"
...
Match
>>>
>>> if re.compile("cde").search("ABCDEF"): print "Match"
...
>>> if re.compile("cde", re.I).search("ABCDEF"): print "Match"
...
Match
>>> 

何がマッチしたのか?


>>> 
>>> src = '----123a456----7b8--901c23--'
>>> mo = re.compile('\d+[a-z]\d+').search(src)
>>> mo.group()
'123a456'
>>> 
>>> mo = re.compile('(\d+)[a-z](\d+)').search(src)
>>> mo.group()
'123a456'
>>> mo.group(1)
'123'
>>> mo.group(2)
'456'
>>> 
>>> mo = re.compile('(\d+)[a-z](\d+)').findall(src)
>>> mo
[('123', '456'), ('7', '8'), ('901', '23')]
>>> 

置換


>>> print re.sub("[ace]", "*", "a-b-c-d-e-f")
*-b-*-d-*-f
>>>
>>> print re.sub("[ace]", "*", "a-b-c-d-e-f", 2)
*-b-*-d-e-f
>>>
>>> print re.compile("[ace]", re.I).sub("*", "A-B-C-D-E-F")
*-B-*-D-*-F
2008年10月24日(金) 15:48:49 Modified by hebi_




スマートフォン版で見る