首页 > 解决方案 > 如何从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>

标签: python

解决方案


你把这$意味着字符串的结尾。尝试这个:

x = re.sub('<style>.*?</style>', '', text, flags=re.DOTALL)
print(x)

你可以看看这个网站,有一个很好的正则表达式演示。

一点提示:我对 CSS 不是很熟悉,所以如果有嵌套<style>标签,可能会出现问题。


推荐阅读