python正则表达式使用样例(二)

发布于:2024-06-04 ⋅ 阅读:(137) ⋅ 点赞:(0)

一、从文本中提取信息

从复杂文本中提取特定信息,例如提取电话号码、日期等:

import re

text = "Contact us at support@example.com or call us at (555) 123-4567"

email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
phone_pattern = r'\(\d{3}\) \d{3}-\d{4}'

emails = re.findall(email_pattern, text)
phones = re.findall(phone_pattern, text)

print(emails)  # 输出 ['support@example.com']
print(phones)  # 输出 ['(555) 123-4567']

二、去除字符串中的多余空白

清理用户输入或格式化文本:

import re

text = "  This is   a   sentence with   irregular spacing.  "
cleaned_text = re.sub(r'\s+', ' ', text).strip()
print(cleaned_text)  # 输出 This is a sentence with irregular spacing.

三、提取HTML中的内容

从HTML文件或字符串中提取特定内容,例如提取所有链接、标题等:

import re

html = """
<html>
  <head><title>Example Title</title></head>
  <body>
    <h1>Example Header</h1>
    <p>This is an example paragraph.</p>
    <a href="http://example.com">Link</a>
  </body>
</html>
"""

# 提取所有链接
links = re.findall(r'href="(http[s]?://.*?)"', html)
print(links)  # 输出 ['http://example.com']

# 提取标题
title = re.search(r'<title>(.*?)</title>', html)
if title:
    print(title.group(1))  # 输出 Example Title

四、验证密码强度

验证用户输入的密码是否符合强度要求,例如包含大小写字母、数字和特殊字符:

import re

def is_strong_password(password):
    pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'
    return re.match(pattern, password) is not None

password = "StrongPass1!"
print(is_strong_password(password))  # 输出 True


网站公告

今日签到

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