Chinaunix首页 | 论坛 | 博客
  • 博客访问: 104514
  • 博文数量: 67
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 577
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-16 09:51
个人简介

啄木鸟专吃虫,故名啄木鸟。

分类: Python/Ruby

2014-05-06 11:17:50

>>> import re
>>> text = 'hm...err --are you surehe said sounding insecure.'
>>> pat = '[a-zA-Z]'
>>> re.findall(pat,text)#以列表形式返回给定模式的匹配项
['h', 'm', 'e', 'r', 'r', 'a', 'r', 'e', 'y', 'o', 'u', 's', 'u', 'r', 'e', 'h', 'e', 's', 'a', 'i', 'd', 's', 'o', 'u', 'n', 'd', 'i', 'n', 'g', 'i', 'n', 's', 'e', 'c', 'u', 'r', 'e']
>>> pat = '[a-zA-Z]+'
>>> re.findall(pat,text)
['hm', 'err', 'are', 'you', 'surehe', 'said', 'sounding', 'insecure']
>>> pat = r'[.?-",]+'
>>> re.findall(pat,text)#为什么会报错?,那是因为 - 没有转义,而不存在?-“这样一个范围
error: bad character range
>>> pat = r'[.?\-",]+'
>>> re.findall(pat,text)
['...', '--', '.']


>>> pat = '{name}'
>>> text = 'dear {name}...'
>>> re.findall(pat,text)
['{name}']
>>> re.sub(pat,'gumby',text)#用gumble替换匹配模式的字符串
'dear gumby...'
>>> text = 'dear name ...'
>>> re.escape('')#这个最有用了,可以将所有可能解释为正则运算符的字符进行转义,看结果就知道了
'www\\.python\\.org'
>>>re.escape('i am a beautiful girl?')
'i\\ am\\ a\\ beautiful\\ girl\\?'


阅读(186) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~