python regex用法
在 Python 中,使用正则表达式(Regex)可以实现对字符串的模式匹配和搜索。Python 提供了 `re` 模块来处理正则表达式,以下是一些基本的 Python 正则表达式的用法:
python正则表达式爬虫导入 re 模块
首先,需要导入 Python 中的 `re` 模块。
import re
正则表达式的基本功能
1. 检查字符串中是否存在匹配模式
pattern = r"apple"
text = "I like apples and oranges."
match = re.search(pattern, text)
if match:
print("Found")
else:
print("Not Found")
2. 匹配字符串中的模式
pattern = r"apple"
text = "I like apples and oranges. Apples are good."
matches = re.findall(pattern, text)
print(matches)  输出所有匹配的字符串列表
3. 替换字符串中的模式
pattern = r"apple"
replacement = "banana"
text = "I like apples and oranges. Apples are good."
new_text = re.sub(pattern, replacement, text)
print(new_text)
正则表达式模式语法
一些常用的正则表达式模式语法:
- `.`:匹配任意字符。
- `^`:匹配字符串的开头。
- `$`:匹配字符串的结尾。
- `[]`:字符集,匹配括号内的任意字符。
- `*`:匹配前一个字符 0 次或多次。
- `+`:匹配前一个字符 1 次或多次。
- `?`:匹配前一个字符 0 次或 1 次。
- `\`:转义特殊字符。
- `()`:捕获组,用于提取匹配的子字符串。
正则表达式方法
- `re.search(pattern, text)`:搜索整个字符串并返回第一个匹配的对象。
- `re.findall(pattern, text)`:返回一个包含所有匹配的字符串列表。
- `re.sub(pattern, replacement, text)`:用替换字符串替换所有匹配的模式。
这些只是正则表达式的基础用法,正则表达式有着丰富的功能和语法,可以实现更加复杂的模式匹配。建议查阅 Python 官方文档或正则表达式教程以深入了解更多内容。