【问题标题】:Modifying a group within Regular Expression Match在正则表达式匹配中修改组
【发布时间】:2014-09-20 04:59:16
【问题描述】:

因此,我的 Django (v 1.5) 模型之外还有一个函数,该函数接受一段文本并查找我的所有标签,例如并将用户正确的标签转换为并删除所有其他标签。

下面的函数目前有效,但需要我使用 note_tags = '.*?\r\n' 因为标签组 0 会找到所有标签,而不管用户的昵称是否在其中。很好奇我将如何使用这些组,以便我可以删除所有无用的标签而无需修改 RegEx。

def format_for_user(self, user):
    body = self.body
    note_tags = '<note .*?>.*?</note>\r\n'
    user_msg = False
    if not user is None:
        user_tags = '(<note %s>).*?</note>' % user.nickname
        user_tags = re.compile(user_tags)
        for tag in user_tags.finditer(body):
            if tag.groups(1):
                replacement = str(tag.groups(1)[0])
                body = body.replace(replacement, '<span>')
                replacement = str(tag.group(0)[-7:])
                body = body.replace(replacement, '</span>')
                user_msg = True
                note_tags = '<note .*?>.*?</span>\r\n'
    note_tags = re.compile(note_tags)
    for tag in note_tags.finditer(body):
        body = body.replace(tag.group(0), '')
    return (body, user_msg)

【问题讨论】:

  • 你是using re to parse your HTML而不是像BeautifulSoup这样的实际HTML库有什么原因吗?并不是说您想要做的事情一定是不可能的,但是考虑到这对于 HTML 库来说是微不足道的,而且您不知道如何编写正则表达式并且必须做一些笨拙的事情,例如剥离前 7 个字符字符串并且您的代码中有一个错误,因为您在可能不止一次发生的事情上使用str.replace 等等......
  • 没有意识到还有其他选择。将检查美丽的汤。

标签: python regex django python-2.7 regex-group


【解决方案1】:

所以 abarnert 是正确的,我不应该使用 Regex 来解析我的 Html,而应该使用 BeautifulSoup 中的东西。

所以我使用了 BeautifulSoup,这是生成的代码,解决了 Regex 遇到的许多问题。

def format_for_user(self, user):
    body = self.body
    soup = BeautifulSoup(body)
    user_msg = False
    if not user is None:
        user_tags = soup.findAll('note', {"class": "%s" % user.nickname})
        for tag in user_tags:
            tag.name = 'span'
    all_tags = soup.findAll('note')
    for tag in all_tags:
        tag.decompose()
    soup = soup.prettify()
    return (soup, user_msg)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    相关资源
    最近更新 更多