正则表达式
正则表达式是一种描述文本模式的语言,Python
通过re
模块提供了对正则表达式的支持,使其成为文本处理、数据洗白和信息提取的强大工具。
正则表达式基本语法
元字符 | 描述 |
---|---|
. |
匹配任意单个字符(除了换行符) |
^ |
匹配字符串的开头 |
$ |
匹配字符串的结尾 |
* |
匹配前面的元素零次或多次 |
+ |
匹配前面的元素一次或多次 |
? |
匹配前面的元素零次或一次 |
[] |
匹配方括号中的任意一个字符 |
() |
分组和捕获 |
\d |
匹配数字,等价于[0-9] |
\w |
匹配字母、数字或下划线,等价于[a-zA-Z0-9_] |
\s |
匹配空白字符 |
re模块核心函数
- match(): 从字符串开头匹配
python
import re
text = "Hello, World!"
match = re.match(r'Hello', text)
if match:
print("匹配成功:", match.group()) # 输出: 匹配成功: Hello
- search(): 搜索整个字符串
python
text = "Price: $19.99"
match = re.search(r'\$\d+\.\d+', text)
if match:
print("找到价格:", match.group()) # 输出: 找到价格: $19.99
- findall():找到所有匹配项
python
text = "Email1: [email protected], Email2: [email protected]"
emails = re.finditer(r'[\w.-]+@[\w.-]+\.\w+', text)
for email in emails:
print("找到邮箱:", email.group())
- finditer():返回匹配的迭代器
python
text = "Email1: [email protected], Email2: [email protected]"
emails = re.finditer(r'[\w.-]+@[\w.-]+\.\w+', text)
for email in emails:
print("找到邮箱:", email.group())
- sub():替换匹配的文本
python
text = "Phone numbers: 123-456-7890, 987-654-3210" masked = re.sub(r'(\d{3})-(\d{3})-(\d{4})', r'\1-***-\4', text) print("掩码后的号码:", masked) # 输出: 掩码后的号码: 123-***-7890, 987-***-3210
正则表达式进阶技巧
- 分组与捕获 使用圆括号() 进行分组,分组可以被引用和捕获
python
text = "Date: 2023-11-15"
match = re.match(r'(\d{4})-(\d{2})-(\d{2})', text)
if match:
year, month, day = match.groups()
print(f"年: {year}, 月: {month}, 日: {day}") # 输出: 年: 2023, 月: 11, 日: 15
match.group()方法是一个管理捕获的一个核心工具,用于捕获匹配对象中的特定部分。当正则表达式成功匹配文本后,match.group()方法允许提取出具体的内容,无论是整个匹配结果还是特定的捕获组。
基本语法: match.group() - 无参数:返回整个匹配的字符串 - 整数参数:返回指定捕获的内容 - 多个参数:返回多个捕获的元祖 - 命名组参数:返回指定命名组的内容
python
import re
# 示例文本
text = "Hello, my email is [email protected] and phone is 123-456-7890."
# 定义一个包含多个捕获组的正则表达式
pattern = r'(\w+)@(\w+\.\w+)|(\d{3})-(\d{3})-(\d{4})'
match = re.search(pattern, text)
if match:
# 0. 检查匹配是否成功
print("匹配成功!")
# 1. 无参数:获取整个匹配内容
print("整个匹配:", match.group()) # 输出: [email protected]
# 2. 单个整数参数:获取特定捕获组
print("捕获组1:", match.group(1)) # 输出: user (邮箱用户名)
print("捕获组2:", match.group(2)) # 输出: example.com (邮箱域名)
# 3. 多个参数:获取多个捕获组
print("捕获组1和2:", match.group(1, 2)) # 输出: ('user', 'example.com')
# 4. 使用groups()方法获取所有捕获组
print("所有捕获组:", match.groups()) # 输出: ('user', 'example.com', None, None, None)
# 5. 捕获组索引从1开始,0表示整个匹配
print("捕获组0:", match.group(0)) # 输出: [email protected]