2014年8月31日日曜日

Python: part6 Regex search vs. group

import reでRegex を読み込みre.seach()で検索、結果はgroupで返答
search()、match()、group()は以下を参照。指定しない場合は区切りなく全て返答。
matchとsearchはmatchは行のはじめからマッチをする必要があるのに対し、searchは途中でもOK。
seachの方が両方にマッチするため便利か。以下のfile1.txtはmatchではマッチしない。

http://www.tutorialspoint.com/python/python_reg_expressions.htm
Match Object MethodsDescription
group(num=0)This method returns entire match (or specific subgroup num)
groups()This method returns all matching subgroups in a tuple (empty if there weren't any)
============================================
kurokawa-no-MacBook-Air:Linux taka$ more file-open3.py
#!/usr/bin/python
import re

f = open ('file1.txt', 'r')
f2 = open ('file2.txt', 'w')

for line in f:
 a = re.search('line-[a-zA-z|0-9]*', line)
 if a:
   f2.write(a.group())
   f2.write('\n')

f.close()
f2.close()

以下は大元のファイル
============================================
kurokawa-no-MacBook-Air:Linux taka$ more file1.txt
a,line-1,c
b,line-23,c
c,line-333a,d
a,line-4444,d
c,line-4a3ac,bb,dd
g,line-2c,33,dd
end

以下は結果で必要なマッチした文字の箇所だけを切り抜く。
============================================
kurokawa-no-MacBook-Air:Linux taka$ more file2.txt
line-1
line-23
line-333a
line-4444
line-4a3ac
line-2c

0 件のコメント:

コメントを投稿