Python中re模块结合正则表达式的应用

发布于:2025-06-04 ⋅ 阅读:(22) ⋅ 点赞:(0)

在 Python 中,re 模块是用于处理正则表达式的标准库。它非常适合用于文本清洗、提取和整理任务。下面是一些常见的使用 re 包结合正则表达式进行文本清洗的方法示例。

re模块常用函数

函数 功能
re.match() 从字符串开头开始匹配
re.search() 在整个字符串中查找第一个匹配项
re.findall() 找出所有匹配的内容,返回列表
re.sub() 替换匹配内容
re.split() 根据正则表达式分割字符串

一、查看文本中是否包含 A 或 B 字符串

import re

text = "这是一个测试字符串,包含apple和banana。"

# 查看是否包含 'apple' 或 'banana'
if re.search(r'apple|banana', text):
    print("包含 apple 或 banana")
else:
    print("不包含")
说明:
r'apple|banana' 是一个正则表达式,表示匹配 “apple” 或者 “banana”
re.search():只要在字符串中有匹配项就返回 True(或匹配对象)

二、替换多个关键词为统一格式

text = "访问网址 www.google.com 或 http://www.baidu.com 获取信息"
cleaned_text = re.sub(r'www\.|http://', '', text)
print(cleaned_text)
# 输出: 访问网址 google.com 或 baidu.com 获取信息

三、提取所有数字

text = "电话号码是1234567890,邮编是100000"
numbers = re.findall(r'\d+', text)
print(numbers)
# 输出: ['1234567890', '100000']

四、去除标点符号

import string

text = "你好!这是一段,含有很多标点?"
pattern = f"[{re.escape(string.punctuation)}]"
cleaned_text = re.sub(pattern, "", text)
print(cleaned_text)
# 输出: 你好这是一段含有很多标点

五、提取中文字符

text = "Hello 你好,世界123"
chinese_chars = re.findall(r'[\u4e00-\u9fa5]+', text)
print(''.join(chinese_chars))
# 输出: 你好世界

六、删除空白字符(空格、换行、制表符等)

text = "  这是一个\t带有很多\n空白的文本  "
cleaned_text = re.sub(r'\s+', ' ', text).strip()
print(cleaned_text)
# 输出: 这是一个 带有很多 空白的文本

七、提取邮箱地址

深色版本
text = "联系我 at example@example.com 或 support@domain.co.cn"
emails = re.findall(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+', text)
print(emails)
# 输出: ['example@example.com', 'support@domain.co.cn']

八、提取 URL 地址

text = "访问 https://example.com 或 http://www.google.com"
urls = re.findall(r'https?://(?:www\.)?\S+', text)
print(urls)
# 输出: ['https://example.com', 'http://www.google.com']

九、保留字母、数字、中文,删除其他字符

text = "这!is a 123_测试-text..."
cleaned_text = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', text)
print(cleaned_text)
# 输出: 这is a 123测试text

十、分词前预处理(小写 + 去除特殊字符)

text = "Hello World! 你好,World!"
cleaned_text = re.sub(r'[^\w\s]|_', '', text).lower()
print(cleaned_text)
# 输出: hello world 你好world

十一、提取手机号码方法(11位数字)

1.提前手机号码

示例目标: 将如 13812345678 格式手机号提取出来,并格式化为 138-1234-5678。

实现代码:

import re

text = "我的电话是13812345678,请在工作时间拨打。另一个号码是13987654321"

# 提取所有11位手机号
phone_numbers = re.findall(r'1\d{10}', text)

# 格式化为 138-1234-5678 样式
formatted_numbers = [re.sub(r'(\d{3})(\d{4})(\d{4})', r'\1-\2-\3', num) for num in phone_numbers]

print(formatted_numbers)
# 输出: ['138-1234-5678', '139-8765-4321']

2.从包含干扰字符的字符串中提取手机号并清理

有时候手机号中可能夹杂着空格、短横线等字符,比如 "138 1234 5678" 或 "139-1234-5678"。 示例代码:

text = "联系方式:138 1234 5678 或 139-1234-5678"

# 去除非数字字符后提取11位手机号
cleaned_numbers = re.findall(r'1\d{10}', re.sub(r'\D', '', text))

# 再格式化输出
formatted_numbers = [re.sub(r'(\d{3})(\d{4})(\d{4})', r'\1-\2-\3', num) for num in cleaned_numbers]

print(formatted_numbers)
# 输出: ['138-1234-5678', '139-1234-5678']

4.添加国家区号并统一格式

如果你需要加上国家区号 +86:

formatted_with_code = ['+86 ' + num for num in formatted_numbers]
print(formatted_with_code)
# 输出: ['+86 138-1234-5678', '+86 139-1234-5678']

5.封装成函数

def format_chinese_phone(text):
    # 清理非数字内容
    cleaned = re.sub(r'\D', '', text)
    # 提取手机号
    phones = re.findall(r'1\d{10}', cleaned)
    # 格式化
    return [re.sub(r'(\d{3})(\d{4})(\d{4})', r'\1-\2-\3', p) for p in phones]

# 使用示例
text = "我的联系电话是:138 1234 5678 和 139-8765-4321"
print(format_chinese_phone(text))
# 输出: ['138-1234-5678', '139-8765-4321']

6.正则说明

正则表达式 含义
\d 匹配任意数字
\D 匹配非数字
{n} 精确匹配 n 次
r'(\d{3})(\d{4})(\d{4})' 分组提取前3位、中间4位、后4位
\1-\2-\3 替换为带连字符的格式

网站公告

今日签到

点亮在社区的每一天
去签到