DW做网站入门步骤教学,游戏网站首页模板,网站怎么记录搜索引擎的关键词,昆山市住房和城乡建设网站正则表达式实战例子
1. 验证电子邮件地址
定义一个合理的电子邮件格式#xff0c;并检查给定的字符串是否符合这个模式。
import redef is_valid_email(email):# 定义电子邮件格式的正则表达式pattern r^[a-zA-Z0-9_.-][a-zA-Z0-9-]\.[a-zA-Z0-9-.]$return bool(re.match(…正则表达式实战例子
1. 验证电子邮件地址
定义一个合理的电子邮件格式并检查给定的字符串是否符合这个模式。
import redef is_valid_email(email):# 定义电子邮件格式的正则表达式pattern r^[a-zA-Z0-9_.-][a-zA-Z0-9-]\.[a-zA-Z0-9-.]$return bool(re.match(pattern, email))# 测试
emails [exampleexample.com, invalid-email, another.validemailexample.co.uk]
for email in emails:print(f{email}: {is_valid_email(email)})2. 提取网页中的所有链接
使用正则表达式来查找HTML文档中所有的a标签及其href属性。
import rehtml_content
a hrefhttp://example.com/page1Link 1/a
a hrefhttp://example.com/page2Link 2/a
a hrefjavascript:void(0)Invalid Link/a
# 匹配带有href属性的a标签并提取href值
link_pattern re.compile(ra\s(?:[^]*?\s)?href[\]([^\]*)[\][^]*)
links link_pattern.findall(html_content)print(Extracted Links:, links)3. 电话号码格式化
电话号码都转换成XXX-XXX-XXXX的形式。
import redef format_phone_number(phone):# 去除非数字字符并确保长度正确cleaned re.sub(r\D, , phone)if len(cleaned) 10:return f{cleaned[:3]}-{cleaned[3:6]}-{cleaned[6:]}else:return Nonephones [(123) 456-7890, 123.456.7890, 1234567890, 123-456-7890]
formatted_phones [format_phone_number(p) for p in phones]
print(formatted_phones)4. 替换敏感信息
掩盖或删除这些敏感信息。这里我们用正则表达式来识别并替换信用卡号。
import redef mask_credit_card(text):# 替换所有连续16位数字的序列信用卡号为****-****-****-1234masked_text re.sub(r\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b,****-****-****-1234, text)return masked_textlog_entry Customer paid with card number 4111-1111-1111-1111.
masked_log mask_credit_card(log_entry)
print(masked_log)5. 解析日志文件
使用正则表达式来解析这些日志条目提取出IP地址、时间戳和请求路径等信息。
import relog_line 127.0.0.1 - - [10/Oct/2023:13:55:36 0000] GET /index.html HTTP/1.1 200 2326# 解析日志条目的正则表达式
log_pattern re.compile(r(\S) (\S) (\S) \[(.*?)\] (.*?) (\d{3}) (\d|-))match log_pattern.match(log_line)
if match:ip_address, _, _, timestamp, request, status_code, size match.groups()print(fIP Address: {ip_address})print(fTimestamp: {timestamp})print(fRequest: {request})print(fStatus Code: {status_code})print(fSize: {size})