python作成正則

1794 ワード

python作成正規使用RE Modules
携帯番号検証

import re
m = re.compile("^\d{7,13}$")
print m.match("18181818")
print m.match("1515")


k= re.compile(u"^(www*|m*)")
print k.search("wwww.f.duitang.com.log").group()

#!/usr/bin/python
import re
str = '1screen12@dsfdsfdsf3" sdf'
#pattern = re.compile('screen.*')      
pattern = re.compile('scree\w*\"') #      
result = pattern.search(str)
print result;

import re
list = []
f = open("log","r") 
post = re.compile("[POST|GET] /[a-zA-Z0-9/?&]*")
hc = re.compile("HTTP/1.1\" \d*")
ma = re.compile("192.168.172.\d+:7199 [0-9.]*")

for read in f.readlines():
	match =  post.search(read)
	if match:
		g = str(match.group()).replace("T","")
		list.append(g)

	match = hc.search(read)
	if match:
		g = str(match.group()).replace("HTTP/1.1\"","")
		list.append(g)
	
	match = ma.search(read)
	if match:
		g = str(match.group())[18:]
		list.append(g)

	list.append("
") print " ".join(list)

出力
返されるこのオブジェクトはMatchObjectで、グループ()などが含まれています.http://docs.python.org/release/2.2.3/lib/match-objects.html
searchメソッドのほかにfindAllメソッドもあります.関連ドキュメントは次のように参照できます.
http://lukejin.iteye.com/blog/608206
http://epydoc.sourceforge.net/stdlib/index.html