2014-09-20 94 views
0

所以我有一个除了我的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) 
+1

有你[使用're'解析您的HTML(原因http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self- contains-tags/1732454#1732454)而不是像'BeautifulSoup'这样的实际HTML库?并不是说你想要做什么是不可能的,但考虑到这对于HTML库来说是微不足道的,而且你不知道如何编写正则表达式,而且必须做一些笨拙的事情,比如剥离掉一个字母的前7个字符字符串和你的代码有一个错误,因为你使用'str.replace'的东西可能会多次出现,等等...... – abarnert 2014-09-20 05:14:21

+0

没有意识到有一个选择。将检查美丽的汤。 – badisa 2014-09-20 19:31:21

回答

0

所以abarnert是正确的,我不应该使用正则表达式来分析我的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)