码迷,mamicode.com
首页 > 其他好文 > 详细

re模块

时间:2018-09-02 14:35:42      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:sea   正则表达   col   ace   att   one   中间   mos   一个   

import re

1.findall  (找所有)

re.findall(‘正则表达式‘,‘匹配对象‘)

  

>>> ret = re.findall([a-z]+,has wodh dsawe)
>>> print(ret)
[has, wodh, dsawe]

 

2.search  (从中间找到也行)

从前往后找,找到一个就返回一个变量,+group()才能显示出结果,不然显示

 

>>> ret = re.search(a,eva gon adsf)
>>> print(ret.group())
a

 

+group()才能显示出结果,不然显示

>>> print(ret)
<re.Match object; span=(2, 3), match=a>

 

如果没找到,会返回None,如果调用group()会报错

>>> ret = re.search(x,eva gon adsf)
>>> print(ret)
None
>>> print(ret.group())
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    print(ret.group())
AttributeError: NoneType object has no attribute group

 

 

3.match    (从开始只找一个)

用法与search一样

 

re模块

标签:sea   正则表达   col   ace   att   one   中间   mos   一个   

原文地址:https://www.cnblogs.com/Hxx0916/p/9573628.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!