博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python正則表達式小结(1)
阅读量:7126 次
发布时间:2019-06-28

本文共 1314 字,大约阅读时间需要 4 分钟。

学习一段python正則表達式了, 对matchsearchfindallfinditer等函数作一小结 

以下以一段网页为例,用python正則表達式作一个范例:

strHtml = '''
'''print strHtml#正則表達式 匹配如:< a href=”xxxxx” class=”xxxx”remod = re.compile(r"

search方法举例

search 会查找第一个找到匹配字符串并返回

item = remod.search(strHtml) if item:    print item.group()else:    print "no match [search]"     # 输出:# 

match方法举例

match 会从字符串开头匹配查找第一个找到匹配字符串并返回

item = remod.match(strHtml, re.M|re.S)   if item:    print item.group()else:print "no match [match]"no match [match] # 输出# no match [match]

findall方法举例

Findall找全部找到匹配字符串并返回一个列表,假设有匹配的组(group),那么它是这个列表下的一个元组

items = remod.findall(strHtml)   if items:    print items    for it in items:        print itelse:    print "no match [findall]"# 输出# [('/user/student/', 'user-t'), ('/common/mobile/search/', 'sch')]# ('/user/student/', 'user-t')# ('/common/mobile/search/', 'sch')

finditer方法举例

finditer找全部找到匹配字符串并返回一个group,能够通过下标引用, 以下从1開始

tems = remod.finditer(strHtml if items:    for it in items:        print "it.group():",it.group()        print "it.group(0):",it.group(0)        print "it.group(1):",it.group(1)        print "it.group(2):",it.group(2)+"\n"else:print "no match [findall]"# 输出# it.group(): 

转载地址:http://bweel.baihongyu.com/

你可能感兴趣的文章
VS2013 创建ASP.NET MVC 4.0 未指定的错误(异常来自HRESULT: 0x80004005(e_fail))
查看>>
iOS在Cocoa Touch Static Library使用CocoaPods
查看>>
[uestc oj]H - 邱老师选妹子
查看>>
Pycharm 出现Unresolved reference '' 错误的解决方法
查看>>
pwnable.kr uaf之wp
查看>>
DG备库无法接受主库归档日志之密码文件
查看>>
关于lodop打印插件
查看>>
如果你迷恋厚实的屋顶,就会失去浩瀚的繁星
查看>>
jQuery鼠标事件例子2的改进
查看>>
Openresty 数据共享API.Data Sharing within an Nginx Worker
查看>>
杭电 2041 超级楼梯
查看>>
个人开发—进度记录(十七)
查看>>
中关村推出“1+6”系列先行先试改革政策
查看>>
【饼干控最不能错过的成就感美味——燕麦提子饼干】
查看>>
[转载] 人工智能:一种现代方法——第3章 用搜索法对问题求解
查看>>
[转载] 民兵葛二蛋——第29集
查看>>
Luogu P2570 [ZJOI2010]贪吃的老鼠
查看>>
使用Jmeter3.1进行接口测试(包含需登录后测试的接口)
查看>>
subset标签过滤集合元素
查看>>
反射机制
查看>>