1. 程式人生 > >python裏使用正則表達式的後向搜索肯定模式

python裏使用正則表達式的後向搜索肯定模式

includes 表達 一個 cli 出現 handle ack detail pop

在前面學習了比較多模式,有前向搜索的,也有後向搜索的,有肯定模式的,也有否定模式的。這次再來學習一個,就是後向搜索肯定模式,意思就是說已經掃描過了的字符串,還想後悔去看一下,是否可以匹配。它的語法是:(?<=pattern)。比如下面的例子,就是用來識別Twitter的賬號,但它這種模式只會匹配,不會出現在匹配的字符串中,如下:

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



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

python裏使用正則表達式的後向搜索肯定模式