python - 如何从python中的给定字符串中删除两个子字符串之间的特定字符串?
问题描述
我正在尝试删除给定字符串中的部分文本。所以问题如下。我有一个字符串。像这样说 HTML 代码。
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
我希望代码删除所有与 CSS 相关的代码。即字符串现在应该如下所示:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
我已经在python中使用这个函数尝试过:
def css_remover(text):
m = re.findall('<style>(.*)</style>$', text,re.DOTALL)
if m:
for eachText in text.split(" "):
for eachM in m:
if eachM in eachText:
text=text.replace(eachText,"")
print(text)
但这不起作用。我希望该函数处理空格、换行符,以便删除<style> </style>
标记之间的所有内容。另外,我希望如果标签上附加了任何单词,它们不会受到影响。喜欢
hello<style> klasjdklasd </style>>
应该屈服hello>
解决方案
你把这$
意味着字符串的结尾。尝试这个:
x = re.sub('<style>.*?</style>', '', text, flags=re.DOTALL)
print(x)
你可以看看这个网站,有一个很好的正则表达式演示。
一点提示:我对 CSS 不是很熟悉,所以如果有嵌套<style>
标签,可能会出现问题。
推荐阅读
- android - 建议购买室内定位系统设备组权
- c# - 比较具有相同类型的对象评估为假
- jquery - 在没有 npm 的 Visual Studio 上将引导程序和 jquery 依赖项添加到 ASP.NET Core 项目
- windows - 有没有办法在ubuntu中创建逻辑图像(.l01)
- ubuntu - 终结者在右键单击、未聚焦(在窗口外单击)等时关闭
- php - 将 Json 文件对象分配给变量
- postgresql - 字符串比较的问题在 Postgres 中包含“_”
- java - java.lang.ClassCastException:java.lang.String 无法转换为 org.json.JSONObject
- javascript - 将附加属性传递给路由器元字段值
- go - 如何创建字符串数组并从 []net.ip 追加数据