加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python正则表达式match和search用法实例

发布时间:2020-12-16 20:14:43 所属栏目:Python 来源:网络整理
导读:本篇章节讲解python正则表达式match和search用法。供大家参考研究。具体分析如下: python提供了2中主要的正则表达式操作:re.match 和 re.search。 match :只从字符串的开始与正则表达式匹配,匹配成功返回matchobject,否则返回none; search :

本篇章节讲解python正则表达式match和search用法。分享给大家供大家参考。具体分析如下:

python提供了2中主要的正则表达式操作:re.match 和 re.search。

match :只从字符串的开始与正则表达式匹配,匹配成功返回matchobject,否则返回none;

search :将字符串的所有字串尝试与正则表达式匹配,如果所有的字串都没有匹配成功,返回none,否则返回matchobject;(re.search相当于perl中的默认行为)

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

PS:关于正则,这里再为大家提供2款本站的正则表达式在线工具供大家参考使用(包正则生成、匹配与验证等):

JavaScript正则表达式在线测试工具:http://tools.aspzz.cn/regex/javascript

正则表达式在线生成工具:http://tools.aspzz.cn/regex/create_reg

希望本文所述对大家的Python程序设计有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读