国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python正則表達(dá)式常用函數(shù)總結(jié)

2020-02-16 01:46:23
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(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)匹配了。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 泌阳县| 麦盖提县| 中西区| 中宁县| 祥云县| 晋江市| 锡林浩特市| 正安县| 丹凤县| 涞水县| 建瓯市| 大安市| 阿尔山市| 吴旗县| 通渭县| 儋州市| 祁阳县| 天镇县| 洪雅县| 乌兰浩特市| 丰台区| 宜黄县| 八宿县| 和龙市| 商南县| 南漳县| 日照市| 广州市| 富源县| 泾源县| 苗栗县| 庆阳市| 资阳市| 密山市| 日土县| 临邑县| 盐池县| 于田县| 巴林左旗| 贵阳市| 融水|