python 爬虫之Re库

正则表达式

正则表达式的特点: 

 

Re库

(减少斜杠的输出)

re.search() 

 

>>> import re
>>> match = re.search(r'[1-9]\d{5}','BIT 100081')
>>> if match:
...     print(match.group(0))
...
100081
>>>

re.match()

>>> match = re.match(r'[1-9]\d{5}','BIT 100081')
>>> if match:
...     print(match.group(0))
...

>>> print(match.group(0))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>>

【没有匹配到,match为空】

>>> match = re.match(r'[1-9]\d{5}','100081 BIT')
>>> if match:
...     print(match.group(0))
...
100081
>>>

re.findall 

re.split()

>>> import re
>>> re.split(r'[1-9]\d{5}','BIT100081 TSU100084')
['BIT', ' TSU', '']
>>>
>>> re.split(r'[1-9]\d{5}','BIT100081 TSU100084',maxsplit=1)
['BIT', ' TSU100084']
>>>

re.finditer()

>>> for m in re.finditer(r'[1-9]\d{5}','BIT100081 TSU100084'):
...     if m :
...             print(m.group(0))
...
100081
100084
>>>

【迭代】

re.sub()

>>> import re
>>> re.sub(r'[1-9]\d{5}',':zipcode','BIT100081 TSU100084')
'BIT:zipcode TSU:zipcode'
>>>

re.compile()

(使用这种方法时不需要再提供正则表达式)

match对象

>>> import re
>>> m = re.search(r'[1-9]\d{5}','BIT100081 TSU100084')
>>> m.string
'BIT100081 TSU100084'
>>> m.re
re.compile('[1-9]\\d{5}')
>>> m.pos
0
>>> m.endpos
19
>>> m.group(0)
'100081'
>>> m.start()
3
>>> m.end()
9
>>> m.span()
(3, 9)
>>>

 贪婪匹配和最小匹配

【加问号】

总结:

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值