Python分组反向引用

时间:2013-09-18 21:57:26

标签: python html regex html-parsing

我正在清理可能源于WYSIWYG的某些html的输出。为了理智,我想摆脱一堆空格式标签。

e.g。

<em></em> Here's some text <strong>   </strong> and here's more <em> <span></span></em>

感谢Regular-Expressions.info,我有一个整洁的正则表达式,反向引用一次打开一个层

# Returns a string minus one level of empty formatting tags
def remove_empty_html_tags(input_string):
    return re.sub(r'<(?P<tag>strong|span|em)\b[^>]*>(\s*)</(?P=tag)>', r'\1', input_string)

但是,我希望能够为<em> <span></span></em>一次解包所有图层,并且可能有5层以上的嵌套空标记。

有没有办法对back (?:<?P<tagBackRef>strong|span|em)\b[^>]>(\s)*)+(或其他内容)进行分组,稍后使用(</(?P=tagBackRef>)+来删除多个嵌套但匹配的空html代码?

后人:

这可能是XY Question,其中我希望用于我想要的结果的工具不是其他任何人都会选择的。 Henry's answer回答了这个问题,但是他和其他所有人都会指出你在一个正则表达式上的html解析器来解析html。 =)

2 个答案:

答案 0 :(得分:4)

使用HTML解析器(例如BeautifulSoup)更容易,例如:

from bs4 import BeautifulSoup

soup = BeautifulSoup("""
<body>
    <em></em> Here's some <span><strong>text</strong></span> <strong>   </strong> and here's more <em> <span></span></em>
</body>
""")

for element in soup.findAll(name=['strong', 'span', 'em']):
    if element.find(True) is None and (not element.string or not element.string.strip()):
        element.extract()

print soup

打印:

<html><body>
 Here's some <span><strong>text</strong></span>  and here's more <em> </em>
</body></html>

如您所见,所有spanstrongem标记都已删除(或仅包含空格)内容。

另见:

答案 1 :(得分:1)

如果你真的不想使用HTML parser,而且你并不过分担心速度(我认为你不是,或者你不会使用正则表达式来清理HTML)您只需修改已编写的代码即可。只需将您的替换置于循环(或递归;您的偏好)中,并在不更改任何内容时返回。

# Returns a string minus all levels of empty formatting tags
def remove_empty_html_tags(input_string):
    matcher = r'<(?P<tag>strong|span|em)\b[^>]*>(\s*)</(?P=tag)>'
    old_string = input_string
    new_string = re.sub(matcher, r'\1', old_string)
    while new_string != old_string:
        old_string = new_string
        new_string = re.sub(matcher, r'\1', new_string)
    return new_string