龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > python编程 >

Python入门篇之正则表达式(3)

时间:2014-10-21 11:48来源:网络整理 作者:网络 点击:
分享到:
复制代码 代码如下: str = 'The dog on my bed' rep = re.sub('dog','cat',str) print rep The cat on my bed replace参数可接受函数。要获得替换的次数,可使用subn()函数。subn()函

 

复制代码 代码如下:

>>> str = 'The dog on my bed'
>>> rep = re.sub('dog','cat',str)
>>> print rep
The cat on my bed

replace参数可接受函数。要获得替换的次数,可使用subn()函数。subn()函数返回一个元组,此元组包含替换了的文本和替换的次数。
 
如果需用同一个正则式进行多次匹配操作,我们可把正则式编译成内部语言,提高处理速度。编译正则式用compile()函数来实现。compile()函数的基本格式如下:
 compile(str[,flags])
 
str表示需编译的正则式串,flags是修饰标志符。正则式被编译后生成一个对象,该对象有多种方法和属性。
 
正则式对象方法/属性

方法/属性 描述
r.search(string[,pos[,endpos]]) 同search()函数,但此函数允许指定搜索的起点和终点
r.match(string[,pos[,endpos]]) 同match()函数,但此函数允许指定搜索的起点和终点
r.split(string[,max]) 同split()函数
r.findall(string) 同findall()函数
r.sub(replace,string[,count]) 同sub()函数
r.subn(replace,string[,count]) 同subn()函数
r.flags 创建对象时定义的标志
r.groupindex 将r'( Pid)'定义的符号组名字映射为组序号的字典
r.pattern 在创建对象时使用的模式

转义字符串用re.escape()函数。
 
通过getattr获取对象引用
 

复制代码 代码如下:

>>> li=['a','b']
>>> getattr(li,'append')
>>> getattr(li,'append')('c')          #相当于li.append('c')
>>> li
['a', 'b', 'c']
>>> handler=getattr(li,'append',None)
>>> handler
<built-in method append of list object at 0xb7d4a52c>
>>> handler('cc')                      #相当于li.append('cc')
>>> li
['a','b','c','cc']
>>>result = handler('bb')
>>>li
['a','b','c','cc','bb']
>>>print result
None

精彩图集

赞助商链接