Python正則表達(dá)式的幾種匹配方法
我們在計(jì)算機(jī)應(yīng)用方面經(jīng)常會遇到很多的困難,例如下面列出Python正則表達(dá)式,就Python正則表達(dá)式中經(jīng)常出現(xiàn)的問題我們給出以下的幾種匹配用法,希望大家在這篇文章中對Python正則表達(dá)式有一個更好的了解。
1.測試正則表達(dá)式是否匹配字符串的全部或部分
- regex=ur"" #正則表達(dá)式
- if re.search(regex, subject):
- do_something()
- else:
- do_anotherthing()
2.測試正則表達(dá)式是否匹配整個字符串
- regex=ur"\Z" #正則表達(dá)式末尾以\Z結(jié)束
- if re.match(regex, subject):
- do_something()
- else:
- do_anotherthing()
3.創(chuàng)建一個匹配對象,然后通過該對象獲得匹配細(xì)節(jié)(Create an object with details about how the regex matches (part of) a string)
- regex=ur"" #正則表達(dá)式
- match = re.search(regex, subject)
- if match:
- # match start: match.start()
- # match end (exclusive): atch.end()
- # matched text: match.group()
- do_something()
- else:
- do_anotherthing()
4.獲取正則表達(dá)式所匹配的子串(Get the part of a string matched by the regex)
- regex=ur"" #正則表達(dá)式
- match = re.search(regex, subject)
- if match:
- result = match.group()
- else:
- result = ""
5. 獲取捕獲組所匹配的子串(Get the part of a string matched by a capturing group)
- regex=ur"" #正則表達(dá)式
- match = re.search(regex, subject)
- if match:
- result = match.group"groupname")
- else:
- result = ""
6. 獲取有名組所匹配的子串(Get the part of a string matched by a named group)
【編輯推薦】