繁体   English   中英

在正则表达式匹配中修改组

[英]Modifying a group within Regular Expression Match

因此,除了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)

所以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)

暂无
暂无

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

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