cfmonkey的笔记本

Python Regex Cheatsheet

import re
def regexp():
    s
= '<html><head><title>Title</title>'
   
# with pre compiled pattern
   
pattern = re.compile('title')
    match
= pattern.search(s)
   
#check for existence
   
print match
   
# >> <_sre.SRE_Match object at 0x011E0E58> #loop through all matches
    match = pattern.findall(s)
   
print match
   
# >> ['title', 'title'] #grouping matches
   
s = '<html><head><title>Title</title>'
    pattern
= re.compile('(head).*(title)')
    match
= pattern.search(s)
   
print match.group(0)
   
# >>head><title>Title</title
   
print match.group(1)
   
# >>head #replace
   
pattern = re.compile('title')
   
print pattern.sub("ersetzt",s)
   
# >> <html><head><ersetzt>Title</ersetzt> #split
   
pattern = re.compile('title')
   
print pattern.split(s)
   
# >> ['<html><head><', '>Title</', '>'] #replace alle lines in file by "eineZeile"
   
f = open('test.txt','r')
    l
= ['eineZeile' for l in f.readlines()]
    f.close()
   
print l
    f
=open("test.txt", "w")
    f.writelines(l)
    f.close() 

regexp()

posted on 2010-09-23 18:31 cfmonkey 阅读(459) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2010年9月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

统计

常用链接

留言簿(2)

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜