【问题标题】:Remove all occurrences in a string except the first occurrence删除字符串中除第一次出现外的所有出现
【发布时间】:2011-12-18 15:04:52
【问题描述】:

在 Python 中,我希望从字符串中删除所有“<html>”(第一次出现的除外)。

另外,我希望从字符串中删除所有“</html>”(最后一次出现的除外)。

<html> 可以是大写,所以我需要它不区分大小写。

我最好的方法是什么?

【问题讨论】:

  • 任何 HTML 开始标签都会有任何属性吗?例如<html xmlns="http://www.w3.org/1999/xhtml" xml:lang=en lang=en>

标签: python regex string


【解决方案1】:

要从字符串s 中删除除第一次出现的<html> 之外的所有内容,您可以使用以下代码:

substr = "<html>"
try:
    first_occurrence = s.index(substr) + len(substr)
except ValueError:
    pass
else:
    s = s[:first_occurrence] + s[first_occurrence:].replace(substr, "")

除最后一次出现的&lt;/html&gt; 之外的所有内容都可以以类似方式删除:

substr = "</html>"
try:
    last_occurrence = s.rindex(substr)
except ValueError:
    pass
else:
    s = s[:last_occurrence].replace(substr, "") + s[last_occurrence:]

您可能希望用空格而不是空字符串替换出现的位置。

【讨论】:

  • 解决方案需要不区分大小写
【解决方案2】:

此解决方案使用两个正则表达式。第一个正则表达式将整个文件/字符串分成三个块:

  1. 第一个块(被捕获到组$1)是从字符串开头到第一个 HTML 开始标记(包括第一个 HTML 开始标记)的所有内容。
  2. 第二个块(被捕获到组$2)是从第一个 HTML 开始标记到最后一个 HTML 结束标记开始的所有内容。
  3. 第三个块(捕获到组 $3)包括最后一个 HTML 结束标记以及文件/字符串末尾的所有内容。

该函数首先尝试将正则表达式与输入文本进行匹配。如果匹配,则使用第二个正则表达式去除最外层 HTML 元素的内容(之前在第 2 组中捕获)的任何 HTML 开始和结束标记。然后使用三个块重新组合字符串(中间块已去除 HTML 标记)。

def stripInnermostHTMLtags(text):
    '''Strip all but outermost HTML start and end tags.
    '''
    # Regex to match outermost HTML element and its contents.
    p_outer = re.compile(r"""
        ^                 # Anchor to start of string.
        (.*?<html[^>]*>)  # $1: Outer HTML start tag.
        (.*)              # $2: Outer HTML element contents.
        (</html\s*>.*)    # $3: Outer HTML end tag.
        $                 # Anchor to end of string.
        """, re.DOTALL | re.VERBOSE | re.IGNORECASE)
    # Split text into outermost HTML tags and its contents.
    m = p_outer.match(text)
    if m:
        # Regex to match HTML element start or end tag.
        p_inner = re.compile("</?html[^>]*>", re.IGNORECASE)
        # Strip contents of any/all HTML start and end tags.
        contents = p_inner.sub("", m.group(2))
        # Put string back together stripped of inner HTML tags.
        text = m.group(1) + contents + m.group(3)
    return text

请注意,此解决方案可以正确处理 HTML 开始标记中可能存在的任何属性。另请注意,此解决方案不处理具有包含 &gt; 字符的属性的 HTML 标记(但这应该非常罕见)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多