本文實例講述了python正則表達式match和search用法。分享給大家供大家參考。具體分析如下:
python提供了2中主要的正則表達式操作:re.match 和 re.search。
match :只從字符串的開始與正則表達式匹配,匹配成功返回matchobject,否則返回none;
search :將字符串的所有字串嘗試與正則表達式匹配,如果所有的字串都沒有匹配成功,返回none,否則返回matchobject;(re.search相當(dāng)于perl中的默認(rèn)行為)
import redef testsearchandmatch(): s1="helloworld, i am 30 !" w1 = "world" m1 = re.search(w1, s1) if m1: print("find : %s" % m1.group()) if re.match(w1, s1) == none: print("cannot match") w2 = "helloworld" m2 = re.match(w2, s1) if m2: print("match : %s" % m2.group())testsearchandmatch()#find : world#cannot match#match : helloworldPS:關(guān)于正則,這里再為大家提供2款本站的正則表達式在線工具供大家參考使用(包正則生成、匹配與驗證等):
JavaScript正則表達式在線測試工具:http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:http://tools.jb51.net/regex/create_reg
希望本文所述對大家的Python程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選