python裏使用正則表達式的後向搜索肯定模式
阿新 • • 發佈:2017-11-12
includes 表達 一個 cli 出現 handle ack detail pop
在前面學習了比較多模式,有前向搜索的,也有後向搜索的,有肯定模式的,也有否定模式的。這次再來學習一個,就是後向搜索肯定模式,意思就是說已經掃描過了的字符串,還想後悔去看一下,是否可以匹配。它的語法是:(?<=pattern)。比如下面的例子,就是用來識別Twitter的賬號,但它這種模式只會匹配,不會出現在匹配的字符串中,如下:
- #python 3.6
- #
- import re
- twitter = re.compile(
- ‘‘‘‘‘
- # A twitter handle: @username
- (?<=@)
- ([\w\d_]+) # username
- ‘‘‘,
- re.VERBOSE)
- text = ‘‘‘‘‘This text includes two Twitter handles.
- One for @caimouse, and one for the author, @caijunsheng.
- ‘‘‘
- print(text)
- for match in twitter.findall(text):
- print(‘Handle:‘, match)
結果輸出如下:
This text includes two Twitter handles.
One for @caimouse, and one for the author, @caijunsheng.
python裏使用正則表達式的後向搜索肯定模式