Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python的正则表达式

作者:苏染瞳°   发布日期:2025-10-07   浏览:48

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)

解释说明:

  1. 示例1:使用正则表达式 r'https?://[^\s]+' 匹配以 httphttps 开头的URL,并提取它们。
  2. 示例2:使用正则表达式 r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+' 验证电子邮件地址的格式。
  3. 示例3:使用正则表达式 r'\d+' 将文本中的所有数字替换为星号 *
  4. 示例4:使用正则表达式 r',\s*' 分割包含逗号和空格的字符串。

上一篇:python sort()

下一篇:python json数组

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站