python 小案例正则表达式

正则表达式是一种用于匹配、查找和替换文本的强大工具。在提取网页中的目标数据时,可以使用正则表达式来搜索和匹配特定模式的文本。

以下是一个使用正则表达式提取网页中的目标数据的示例代码:

复制代码
import re

# 网页源代码
html = """
<div class="title">正则表达式教程</div>
<div class="content">这是一篇关于正则表达式的教程。</div>
<div class="author">作者:小明</div>
"""

# 提取标题
title_pattern = r'<div class="title">(.*?)</div>'
title_match = re.search(title_pattern, html)
if title_match:
    title = title_match.group(1)
    print("标题:", title)

# 提取内容
content_pattern = r'<div class="content">(.*?)</div>'
content_match = re.search(content_pattern, html)
if content_match:
    content = content_match.group(1)
    print("内容:", content)

# 提取作者
author_pattern = r'<div class="author">(.*?)</div>'
author_match = re.search(author_pattern, html)
if author_match:
    author = author_match.group(1)
    print("作者:", author)

运行以上代码,将会输出:

复制代码
标题: 正则表达式教程
内容: 这是一篇关于正则表达式的教程。
作者: 小明

在上述代码中,我们使用了re.search()函数来搜索匹配特定模式的文本。正则表达式的模式使用了特定的语法符号,如.表示任意字符,*表示前面的字符可以重复任意次数,.*?表示非贪婪匹配,()表示分组。通过使用分组,我们可以方便地提取匹配到的目标数据。

需要注意的是,当处理复杂的HTML结构时,正则表达式可能无法很好地处理,建议使用专门的HTML解析库(如BeautifulSoup)来提取网页中的数据。

本文由mdnice多平台发布

相关推荐
杨杨杨大侠4 小时前
Jev、Kev、Laya:决策模型怎么选,什么时候需要微调?
人工智能·python·agent
LOVE️YOU4 小时前
Python 在定义函数时,究竟定义的是什么?
python
段一凡-华北理工大学4 小时前
大模型应用开发 100 天:Python + LLM 从入门到精通 day26~Prompt 调试与优化——A/B 测试与效果评估
windows·python·大模型·prompt·智能体·提示词工程·高炉智能化
Minecraft红客5 小时前
以撒的结合
python·游戏·电脑·娱乐
Circ.5 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
风早爽太5 小时前
用 ‌Render‌ 快速部署网站和常见问题解决
python·fastapi
李航19836 小时前
给自己的图形引擎,配上了AI渲染,做设计真是太方便了
人工智能·python·计算机视觉·ai·ai编程
L@ncor7 小时前
第六章 框架开发实践 · 学习笔记(AutoGen / AgentScope / CAMEL / LangGraph)
python·框架·autogen·langgraph·agentscope
Zhou1411367 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
摇滚侠8 小时前
《On Java 中文版 基础卷》阅读笔记 对象无处不在 03
java·笔记·python