技术文摘
Python 中九个正则表达式使用实例
2024-12-30 23:12:23 小编
Python 中九个正则表达式使用实例
正则表达式在 Python 中是处理文本的强大工具,它允许我们通过模式匹配来搜索、提取和操作文本。以下是九个常见的正则表达式使用实例。
实例一:验证电子邮件地址
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
if re.match(pattern, email):
return True
else:
return False
print(validate_email('example@example.com'))
实例二:提取手机号码
import re
def extract_mobile_number(text):
pattern = r'\b1[3-9]\d{9}\b'
matches = re.findall(pattern, text)
return matches
print(extract_mobile_number('我的手机号是 13812345678,还有 15698765432'))
实例三:匹配日期格式
import re
def match_date(date):
pattern = r'\d{4}-\d{2}-\d{2}'
if re.match(pattern, date):
return True
else:
return False
print(match_date('2023-07-15'))
实例四:去除字符串中的空格
import re
def remove_spaces(text):
return re.sub(r'\s+', '', text)
print(remove_spaces(' Hello World '))
实例五:提取网址
import re
def extract_urls(text):
pattern = r'https?://[^\s]+'
matches = re.findall(pattern, text)
return matches
print(extract_urls('访问这个网站:https://www.example.com 还有另一个:http://example.org'))
实例六:替换特定字符
import re
def replace_special_chars(text):
return re.sub(r'[^\w\s]', '', text)
print(replace_special_chars('Hello, World!'))
实例七:分割字符串
import re
def split_string(text):
return re.split(r'\s+', text)
print(split_string('Hello World How Are You'))
实例八:查找重复单词
import re
def find_duplicated_words(text):
pattern = r'\b(\w+)\s+\1\b'
matches = re.findall(pattern, text)
return matches
print(find_duplicated_words('This is is a test test'))
实例九:提取整数
import re
def extract_integers(text):
pattern = r'\b\d+\b'
matches = re.findall(pattern, text)
return matches
print(extract_integers('There are 10 apples and 20 oranges'))
通过以上九个实例,我们可以看到正则表达式在 Python 中的广泛应用和强大功能。熟练掌握正则表达式将极大地提高我们处理文本的效率和灵活性。
TAGS: Python 编程 Python 正则表达式 编程实践 正则表达式用法
- Python 实现旅游景点信息与评论的获取及词云与数据可视化
- 11 个令人惊叹的 JavaScript 单行代码
- CSS 轻松打造超酷炫转场动画
- 携程酒店 Flutter 性能优化之实践
- 遗留系统服务的拆分策略
- 数据质量的动态探查与前端相关实现
- 前端开发流程的自动化及提效实践
- 并发编程:CompletableFuture 异步编程并非难事
- 本地运用 Docker Compose 和 Nestjs 迅速构建基于 Dapr 的 Redis 发布/订阅分布式应用
- 对线程安全性的独特理解:如此清新脱俗的讲述
- 写出灵活系统竟这般容易!小白也能搞定高级 Java 业务!
- 五类出色的微服务 Java 框架
- 浏览器开发者工具的实用技巧汇总
- Rust备受赞誉,学习之人却为何寥寥?
- 软件设计中缓存的那些事