隨筆記錄方便自己和同路人查閱。
#------------------------------------------------我是可恥的分割線-------------------------------------------
可以在正則表達式的開始處使用插入符號(^),表明匹配必須發生在被查找文本開始處。類似地,可以在正則表達式
末尾加上美元符號($),表示該字符串必須以這個正則表達式的模式結束。可以同時使用(^)和($),表明整個字符串必須匹
配該模式,也就是說,只匹配該字符串的某個子集是不夠的。
#------------------------------------------------我是可恥的分割線-------------------------------------------
1、^匹配開始位置字符串,示例代碼:
#! python 3 # -*- coding:utf-8 -*- # Autor: Li Rong Yang import re beginsWithHello = re.compile(r'^Hello') mo = beginsWithHello.search('Hello world!') print(mo.group())
運行結果:
錯誤示例代碼:
import re beginsWithHello = re.compile(r'^Hello') if beginsWithHello.search('He said hello.') == None: print('True')
運行結果:
2、$匹配結束位置字符串,示例代碼:
#! python 3 # -*- coding:utf-8 -*- # Autor: Li Rong Yang import re beginsWithHello = re.compile(r'world!$')#使用$美元符檢查結束位置是否符合該內容 mo = beginsWithHello.search('Hello world!') print(mo.group())
運行結果:
錯誤示例代碼:
#! python 3 # -*- coding:utf-8 -*- # Autor: Li Rong Yang import re beginsWithHello = re.compile(r'Hello$')#使用$美元符檢查結束位置是否符合該內容 if beginsWithHello.search('Hello world!') ==None: print('True')
運行結果: