python里使用正则表达式

在前面学习了比较多模式,有前向搜索的,也有后向搜索的,有肯定模式的,也有否定模式的。这次再来学习一个,就是后向搜索肯定模式,意思就是说已经扫描过了的字符串,还想后悔去看一下,是否可以匹配。它的语法是:(?<=pattern)。比如下面的例子,就是用来识别Twitter的账号,但它这种模式只会匹配,不会出现在匹配的字符串中,如下:
 
[python]  view plain  copy
  1. #python 3.6  
  2. #蔡军生   
  3. #http://www.m4493.com 
  4. #  
  5. import re  
  6.   
  7. twitter = re.compile(  
  8.     ''''' 
  9.     # A twitter handle: @username 
  10.     (?<=@) 
  11.     ([\w\d_]+)       # username 
  12.     ''',  
  13.     re.VERBOSE)  
  14.   
  15. text = '''''This text includes two Twitter handles. 
  16. One for @caimouse, and one for the author, @caijunsheng. 
  17. '''  
  18.   
  19. print(text)  
  20. for match in twitter.findall(text):  
  21.     print('Handle:', match)  


 结果输出如下:
 This text includes two Twitter handles.
One for @caimouse, and one for the author, @caijunsheng.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值