# -*- coding: utf-8 -*- import re s = "10 0x14 30 0x28 50 0x3c" pattern = "[0][xX][0-9a-fA-F]+" # パターンを正規表現オブジェクトにコンパイルする re_obj = re.compile(pattern) # 結果を返す match = re_obj.match(s) search = re_obj.search(s) split = re_obj.split(s) findall = re_obj.findall(s) finditer = re_obj.finditer(s) # subとsubnの引数で渡す # 16進数の文字列を10進数の文字列に変換し返す def repl(match_obj): return str(int(match_obj.group(), 16)) sub = re_obj.sub(repl, s) subn = re_obj.subn(repl, s) print "string='%s'" % s print "pattern='%s'" % pattern print print "match:", match print "search: start=%d, end=%d, group='%s'" % (search.start(), search.end(), search.group()) print "split:", split print "findall:", findall print "finditer:" for match_obj in finditer: print " start=%d, end=%d, group='%s'" % (match_obj.start(), match_obj.end(), match_obj.group()) print "sub: '%s'" % sub print "subn:", subn
実行すると
string='10 0x14 30 0x28 50 0x3c' pattern='[0][xX][0-9a-fA-F]+' match: None search: start=3, end=7, group='0x14' split: ['10 ', ' 30 ', ' 50 ', ''] findall: ['0x14', '0x28', '0x3c'] finditer: start=3, end=7, group='0x14' start=11, end=15, group='0x28' start=19, end=23, group='0x3c' sub: '10 20 30 40 50 60' subn: ('10 20 30 40 50 60', 3)
詳細はドキュメントで
0 件のコメント:
コメントを投稿