python里使用正则表达式

在做亚洲美女图片

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

[python]  view plain  copy
 
 
  1. #python 3.6  
  2. #蔡军生   
  3. # http://www.meimei689.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.

猜你喜欢

转载自yangjiyue.iteye.com/blog/2401091
今日推荐