Python正則表達式十種相關的匹配方法
作者:佚名
Python正則表達式需要我們不斷的學習,在學習中我們會遇到相關匹配的問題。下面我們就看看在實際操作中十種經常遇到的匹配方法。
Python正則表達式需要各種各樣的匹配,但是我們不能盲目的進行相匹配,下面就向大家介紹經常遇到的十種Python正則表達式匹配方式,希望大家有所收獲。
1.測試Python正則表達式是否 匹配字符串的全部或部分
- regex=ur"..." #正則表達式
- if re.search(regex, subject):
- do_something()
- else:
- do_anotherthing()
2.測試Python正則表達式是否匹配整個字符串
- regex=ur"...\Z" #正則表達式末尾以\Z結束
- if re.match(regex, subject):
- do_something()
- else:
- do_anotherthing()
3. 創建一個匹配對象,然后通過該對象獲得匹配細節
- regex=ur"..." #正則表達式
- 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正則表達式所匹配的子串
- regex=ur"..." #正則表達式
- match = re.search(regex, subject)
- if match:
- result = match.group()
- else:
- result = ""
5. 獲取捕獲組所匹配的子串
- regex=ur"..." #正則表達式
- match = re.search(regex, subject)
- if match:
- result = match.group(1)
- else:
- result = ""
6. 獲取有名組所匹配的子串
- regex=ur"..." #正則表達式
- match = re.search(regex, subject)
- if match:
- result = match.group("groupname")
- else:
- result = ""
7. 將字符串中所有匹配的子串放入數組中
- 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正則表達式 字符串創建一個正則表達式對象
- (Create an object to use the same regex for many
operations)- rereobj = re.compile(regex)
10.用法1的Python正則表達式對象版本
- rereobj = re.compile(regex)
- if reobj.search(subject):
- do_something()
- else:
- do_anotherthing()
以上就是對Python正則表達式相關問題匹配的解決方案。
【編輯推薦】
責任編輯:張浩
來源:
IT168