import re
# 示例1:匹配以 'http' 或 'https' 开头的URL
url_pattern = r'https?://[^\s]+'
text = "Visit our website at http://example.com or https://secure.example.com."
urls = re.findall(url_pattern, text)
print("找到的URL:", urls)
# 示例2:验证电子邮件格式
email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
email = "test@example.com"
if re.match(email_pattern, email):
print(f"{email} 是有效的电子邮件地址")
else:
print(f"{email} 不是有效的电子邮件地址")
# 示例3:替换文本中的所有数字为 '*'
text_with_numbers = "The price is 100 dollars and the quantity is 5."
cleaned_text = re.sub(r'\d+', '*', text_with_numbers)
print("替换后的文本:", cleaned_text)
# 示例4:分割字符串
text_to_split = "apple, orange, banana, grape"
result = re.split(r',\s*', text_to_split)
print("分割后的结果:", result)
r'https?://[^\s]+'
匹配以 http
或 https
开头的URL,并提取它们。r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
验证电子邮件地址的格式。r'\d+'
将文本中的所有数字替换为星号 *
。r',\s*'
分割包含逗号和空格的字符串。上一篇:python sort()
下一篇:python json数组
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站