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

yipeiwu_com6年前Python基础

本文实例讲述了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.jb51.net/regex/javascript

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

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

相关文章

Python字典推导式将cookie字符串转化为字典解析

cookie: PHPSESSID=et4a33og7nbftv60j3v9m86cro; Hm_lvt_51e3cc975b346e7705d8c255164036b3=156155...

python在控制台输出进度条的方法

本文实例讲述了python在控制台输出进度条的方法。分享给大家供大家参考。具体实现方法如下: 进度条效果如下所示: |#############################---...

python 自动去除空行的实例

code 原文档 1.txt : Hello Nanjing 100 实现代码: file_ = "1.txt" r_file = open(file_, "r"...

python 实现方阵的对角线遍历示例

任务描述 对一个方阵矩阵,实现平行于主对角线方向的对角线元素遍历。 从矩阵索引入手: [[ 1 2 3 4 5] [ 6 7 8 9 10] [11 12 13 14 15]...

python dataframe NaN处理方式

将dataframe中的NaN替换成希望的值 import pandas as pd df1 = pd.DataFrame([{'col1':'a', 'col2':1}, {'co...