本文實(shí)例總結(jié)了Python正則表達(dá)式常用函數(shù)。分享給大家供大家參考,具體如下:
re.match()
函數(shù)原型:
match(pattern, string, flags=0)    Try to apply the pattern at the start of the string,
     returning a match object, or None if no match was found.
函數(shù)作用:
re.match函數(shù)嘗試從字符串的開(kāi)頭開(kāi)始匹配一個(gè)模式,如果匹配成功,返回一個(gè)匹配成功的對(duì)象,否則返回None。
參數(shù)說(shuō)明:
pattern:匹配的正則表達(dá)式
string:要匹配的字符串
flags:標(biāo)志位,用于控制正則表達(dá)式的匹配方式。如是否區(qū)分大小寫(xiě)、是否多行匹配等。
我們可以使用group()或groups()匹配對(duì)象函數(shù)來(lái)獲取匹配后的結(jié)果。
group()
group(...)    group([group1, ...]) -> str or tuple.
    Return subgroup(s) of the match by indices or names.
    For 0 returns the entire match.
獲得一個(gè)或多個(gè)分組截獲的字符串;指定多個(gè)參數(shù)時(shí)將以元組形式返回。group1可以使用編號(hào)也可以使用別名;編號(hào)0代表匹配的整個(gè)子串;默認(rèn)返回group(0);沒(méi)有截獲字符串的組返回None;截獲了多次的組返回最后一次截獲的子串。
groups()
groups(...)    groups([default=None]) -> tuple.
    Return a tuple containing all the subgroups of the match, from 1.
    The default argument is used for groups
    that did not participate in the match
以元組形式返回全部分組截獲的字符串。相當(dāng)于調(diào)用group(1,2,…last)。沒(méi)有截獲字符串的組以默認(rèn)值None代替。
實(shí)例
import reline = "This is the last one"res = re.match( r'(.*) is (.*?) .*', line, re.M|re.I)if res: print "res.group() : ", res.group() print "res.group(1) : ", res.group(1) print "res.group(2) : ", res.group(2) print "res.groups() : ", res.groups()else: print "No match!!"
re.M|re.I:這兩參數(shù)表示多行匹配|不區(qū)分大小寫(xiě),同時(shí)生效。
細(xì)節(jié)實(shí)例:
>>> re.match(r'.*','.*g3jl/nok').group()'.*g3jl'
.(點(diǎn))表示除換行符以外的任意一個(gè)字符,*(星號(hào))表示匹配前面一個(gè)字符0次1次或多次,這兩聯(lián)合起來(lái)使用表示匹配除換行符意外的任意多個(gè)字符,所以出現(xiàn)以上的結(jié)果。
1、re.match(r'.*..', '..').group()'..'2、>>> re.match(r'.*g.','.*g3jlok').group()'.*g3'3、>>> re.match(r'.*...', '..').group()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'NoneType' object has no attribute 'group'
上面兩例子為什么有結(jié)果呢?這是因?yàn)榈谝粋€(gè)例子.*..中的.*匹配了0次,后面的..匹配字符串中..,而第二個(gè)例子中的 .* 匹配了一次,匹配字符串中的 .*,g匹配了后面的g字符,最后一個(gè).號(hào)匹配了。
新聞熱點(diǎn)
疑難解答
圖片精選