python里使用正则表达式的后向搜索肯定模式

在前面学习了比较多模式,有前向搜索的,也有后向搜索的,有肯定模式的,也有否定模式的。这次再来学习一个,就是后向搜索肯定模式,意思就是说已经扫描过了的字符串,还想后悔去看一下,是否可以匹配。它的语法是:(?<=pattern)。比如下面的例子,就是用来识别Twitter的账号,但它这种模式只会匹配,不会出现在匹配的字符串中,如下:
 

[python]  view plain  copy
 
  1. #python 3.6  
  2. #  
  3. import re  
  4.   
  5. twitter = re.compile(  
  6.     ''''' 
  7.     # A twitter handle: @username 
  8.     (?<=@) 
  9.     ([\w\d_]+)       # username 
  10.     ''',  
  11.     re.VERBOSE)  
  12.   
  13. text = '''''This text includes two Twitter handles. 
  14. One for @caimouse, and one for the author, @caijunsheng. 
  15. '''  
  16.   
  17. print(text)  
  18. for match in twitter.findall(text):  
  19.     print('Handle:', match)  



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

转载于:https://www.cnblogs.com/zou272/p/7822790.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值