欢迎访问宙启技术站
智能推送

Python爬虫常用的正则表达式函数

发布时间:2023-06-05 05:49:55

正则表达式是一种强大的工具,使用它可以快速有效地从文本中提取想要的数据。在Python爬虫中,使用正则表达式是非常常见的操作,因此,本文将介绍Python爬虫常用的正则表达式函数。

1. re.match()

re.match()函数用于从字符串的起始位置开始匹配一个模式,只匹配 个符合条件的字符串。

语法:re.match(pattern, string, flags=0)

其中,pattern是正则表达式,string是待匹配的字符串,flags是匹配模式参数。

示例:

import re

string = 'Hello, World!'

pattern = r'Hello'

result = re.match(pattern, string)

print(result.group()) # 输出Hello

2. re.search()

re.search()函数用于在字符串中搜索匹配的子串,只匹配 个符合条件的字符串。

语法:re.search(pattern, string, flags=0)

其中,pattern是正则表达式,string是待匹配的字符串,flags是匹配模式参数。

示例:

import re

string = 'Hello, World!'

pattern = r'World'

result = re.search(pattern, string)

print(result.group()) # 输出World

3. re.findall()

re.findall()函数用于从字符串中搜索所有符合条件的子串,并以列表的形式返回所有满足条件的子串。

语法:re.findall(pattern, string, flags=0)

其中,pattern是正则表达式,string是待匹配的字符串,flags是匹配模式参数。

示例:

import re

string = 'Hello, World!'

pattern = r'l'

result = re.findall(pattern, string)

print(result) # 输出['l', 'l']

4. re.sub()

re.sub()函数用于在字符串中替换所有符合条件的子串,返回替换后的字符串。

语法:re.sub(pattern, repl, string, count=0, flags=0)

其中,pattern是正则表达式,repl是要替换成的字符串,string是待匹配的字符串,count是替换次数(默认为0,表示全部替换),flags是匹配模式参数。

示例:

import re

string = 'Hello, World!'

pattern = r'l'

repl = 'L'

result = re.sub(pattern, repl, string)

print(result) # 输出HeLLo, WorLD!

5. re.compile()

re.compile()函数用于将正则表达式编译成一个Pattern对象,以便在后续使用时可以更快速地匹配和搜索。

语法:re.compile(pattern, flags=0)

其中,pattern是正则表达式,flags是匹配模式参数。

示例:

import re

string = 'Hello, World!'

pattern = r'l'

compiled_pattern = re.compile(pattern)

result = compiled_pattern.findall(string)

print(result) # 输出['l', 'l']

以上就是Python爬虫常用的正则表达式函数。通过使用这些函数,我们可以更加方便地进行文本抓取和数据处理。