Python正則表達(dá)式十種相關(guān)的匹配方法
Python正則表達(dá)式需要各種各樣的匹配,但是我們不能盲目的進(jìn)行相匹配,下面就向大家介紹經(jīng)常遇到的十種Python正則表達(dá)式匹配方式,希望大家有所收獲。
1.測試Python正則表達(dá)式是否 匹配字符串的全部或部分
- regex=ur"..." #正則表達(dá)式
- if re.search(regex, subject):
- do_something()
- else:
- do_anotherthing()
2.測試Python正則表達(dá)式是否匹配整個字符串
- regex=ur"...\Z" #正則表達(dá)式末尾以\Z結(jié)束
- if re.match(regex, subject):
- do_something()
- else:
- do_anotherthing()
3. 創(chuàng)建一個匹配對象,然后通過該對象獲得匹配細(xì)節(jié)
- regex=ur"..." #正則表達(dá)式
- match = re.search(regex, subject)
- if match:
- # match start: match.start()
- # match end (exclusive): match.end()
- # matched text: match.group()
- do_something()
- else:
- do_anotherthing()
4.獲取Python正則表達(dá)式所匹配的子串
- regex=ur"..." #正則表達(dá)式
- match = re.search(regex, subject)
- if match:
- result = match.group()
- else:
- result = ""
5. 獲取捕獲組所匹配的子串
- regex=ur"..." #正則表達(dá)式
- match = re.search(regex, subject)
- if match:
- result = match.group(1)
- else:
- result = ""
6. 獲取有名組所匹配的子串
- regex=ur"..." #正則表達(dá)式
- match = re.search(regex, subject)
- if match:
- result = match.group("groupname")
- else:
- result = ""
7. 將字符串中所有匹配的子串放入數(shù)組中
- reresult = re.findall(regex, subject)
8.遍歷所有匹配的子串
- (Iterate over all matches in a string)
- for match in re.finditer(r"<(.*?)\s*.*?/\1>", subject)
- # match start: match.start()
- # match end (exclusive): match.end()
- # matched text: match.group()
9.通過Python正則表達(dá)式 字符串創(chuàng)建一個正則表達(dá)式對象
- (Create an object to use the same regex for many
operations)- rereobj = re.compile(regex)
10.用法1的Python正則表達(dá)式對象版本
- rereobj = re.compile(regex)
- if reobj.search(subject):
- do_something()
- else:
- do_anotherthing()
以上就是對Python正則表達(dá)式相關(guān)問題匹配的解決方案。
【編輯推薦】