第15章 正则表达式(3)

15.3.10 从字符串的开头或结尾匹配及在单词边界上的匹配

>>> m = re.search('^The', 'The end.')
>>> if m is not None:
... 	m.group()
... 	
'The'
>>> 
>>> m = re.search(r'\bthe', 'here is the dog!')
>>> if m is not None:
... 	print m.group()
... 	
the
>>> 
15.3.11 用findall()找到每个出现的匹配部分

它用于非重叠地搜索某字符串中一个正则表达式模式出现的情况。如果findall()没有找到匹配的部分,会返回空列表;如果成功找到匹配部分,则返回所有匹配部分的列表(按从左到右出现的顺序排列)。

>>> `re.findall('Xufei|Xuyang', 'Xufei Fan and Xuyang Fan')`
"['Xufei', 'Xuyang']"
>>> 
15.3.12 用sub()(和subn())进行搜索和替换

sub()和subn()都是将某字符串中所有匹配正则表达式模式的部分进行替换。用来替换的部分通常是一个字符串。subn()和sub()一样,但它还返回一个表示替换次数的数字,替换后的字符串和表示替换次数的数字作为一个元组的元素返回。

>>> `re.sub("Xufei", 'Anders', "Xufei Fan  Xufei Fan")`
"'Anders Fan  Anders Fan'"
>>> `re.subn("Xufei", 'Anders', "Xufei Fan  Xufei Fan")`	
"('Anders Fan  Anders Fan', 2)"
>>> 
15.3.13 用split()分割(分隔模式)

>>> `re.split(':', 'str1:str2:str3')`
"['str1', 'str2', 'str3']"
>>> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值