繁体   English   中英

如何从python中的给定字符串中删除两个子字符串之间的特定字符串?

[英]How to remove specific string between two substrings from given string in 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>标签,可能会出现问题。

特别注意? RegExp表达式的<style>(.*?)</style>部分中的字符,以免过于“贪婪”。 否则,在下面的示例中,它还将删除<title> HTML标记。

import re

text = """
<!DOCTYPE html>
<html>
  <head>
    <style>
    body {background-color: powderblue;}
    h1   {color: blue;}
    p    {color: red;}
    </style>
    <title>Test</title>
    <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>
"""

regex = re.compile(r' *<style>(.*?)</style> *\n?', re.DOTALL|re.MULTILINE)
text = regex.sub('', text, 0)

print (text == """
<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
  </head>

  <body>

  <h1>This is a heading</h1>
  <p>This is a paragraph.</p>

  </body>
</html>
""")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM