各位用户为了找寻关于python正则表达式match和search用法实例的资料费劲了很多周折。这里教程网为您整理了关于python正则表达式match和search用法实例的相关资料,仅供查阅,以下为您介绍关于python正则表达式match和search用法实例的详细内容
本文实例讲述了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 17import
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程序设计有所帮助。