python爬虫的re库(正则表达式匹配)

re库是python中自带的一个库,不需要外部导入。

它主要是支持正则表达式匹配。

下面来说一下其主要功能函数:

函数 说明
re.search() 在一个字符串中搜索匹配正则表达式的第一个位置,返回match对象。
re.match() 在一个字符串的开始位置起匹配表达式,返回match对象
re.findall() 搜索字符串,以列表类型返回全部能匹配的子串
re.split() 将一个字符串按照正则表达式的匹配结果进行分割,返回列表类型
re.finditer() 搜索字符串,返回一个匹配结果的迭代类型,每个迭代元素是match对象
re.sub() 在一个字符串中替换所有匹配正则表达式的子串,返回替换后的字符串

正则表达式使用标记:

常用标记 说明
re.I re.IGNORECASE 忽略正则表达式的大小写 【A-Z】能够匹配小写字符
re.M re.MULITILINE 正则表达式中的^操作符能够将给定字符串的每行当作匹配开始
re.S re.DOTALL 正则表达式中的.操作符能够匹配所有字符,默认匹配除换行外的所有字符
import re
match = re.search(r'[1-9]\d{5}','BIT 100081')
if match:
    print(match.group(0))

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

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

返回结果:

100081
100081

Process finished with exit code 0

第三个不返回 结果 因为他是从第一个开始匹配 很明显第一个字母B和它的正则表达式不匹配,所以结果为空,那么if判断之后 将不会输出。

import re

ls = re.findall(r'[1-9]\d{5}', 'BIT100081 FSABIT100085')
if ls:
    print(ls)

ls = re.split(r'[1-9]\d{5}', 'BIT100081 FSABIT100085')
if ls:
    print(ls)
ls = re.split(r'[1-9]\d{5}', 'BIT100081 FSABIT100085',maxsplit=1)
if ls:
    print(ls)

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

ls = re.sub(r'[1-9]\d{5}', ':zipcode', 'BIT100081 FSABIT100085')
print(ls)

输出结果:

['100081', '100085']
['BIT', ' FSABIT', '']
['BIT', ' FSABIT100085']
100081
100085
BIT:zipcode FSABIT:zipcode

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/k_koris/article/details/83998894