本文實例講述了python正則表達式match和search用法。分享給大家供大家參考。具體分析如下:
python提供了2中主要的正則表達式操作:re.match 和 re.search。
match :只從字符串的開始與正則表達式匹配,匹配成功返回matchobject,否則返回none;
search :將字符串的所有字串嘗試與正則表達式匹配,如果所有的字串都沒有匹配成功,返回none,否則返回matchobject;(re.search相當于perl中的默認行為)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import re def 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 : helloworld |
希望本文所述對大家的Python程序設計有所幫助。