import re
# 示例1:匹配以 "http" 或 "https" 开头的 URL
url_pattern = r'^(http|https)://[^\s]+'
urls = [
"http://example.com",
"https://example.org",
"ftp://example.net"
]
for url in urls:
if re.match(url_pattern, url):
print(f"匹配成功: {url}")
else:
print(f"匹配失败: {url}")
# 示例2:提取电子邮件地址
email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
text = "请将意见发送至 support@example.com 或 sales@example.org。"
emails = re.findall(email_pattern, text)
print(f"找到的电子邮件地址: {emails}")
# 示例3:替换文本中的指定模式
text = "价格是 $100 和 $200."
price_pattern = r'\$([0-9]+)'
new_text = re.sub(price_pattern, r'¥\1', text)
print(f"替换后的文本: {new_text}")
# 示例4:分割字符串
text = "apple, orange, banana, grape"
split_pattern = r',\s*'
items = re.split(split_pattern, text)
print(f"分割后的列表: {items}")
示例1:使用正则表达式匹配以 "http" 或 "https" 开头的 URL。
r'^(http|https)://[^\s]+'
:^
表示字符串开头,(http|https)
表示匹配 "http" 或 "https",://
是固定的字符序列,[^\s]+
表示一个或多个非空白字符。示例2:使用正则表达式从文本中提取电子邮件地址。
r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
:这是一个常见的电子邮件地址匹配模式,确保了用户名和域名的有效性。示例3:使用正则表达式替换文本中的美元符号为人民币符号。
r'\$([0-9]+)'
:\$
匹配美元符号,([0-9]+)
捕获一个或多个数字,\1
表示引用第一个捕获组。示例4:使用正则表达式分割字符串。
r',\s*'
:匹配逗号后面可能跟随的零个或多个空格,用于分割字符串。希望这些示例能帮助你理解 Python 中正则表达式的用法。
上一篇:python快速编程入门
下一篇:python 字典循环
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站