Python入门篇之正则表达式(3)
>>> 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
- 上一篇:Python入门篇之数字
- 下一篇:Python入门篇之文件