vendredi 19 septembre 2014

Modifying a group within Regular Expression Match


Vote count:

0




So I have a function apart of my Django (v 1.5) Model that takes a body of text and finds all of my tags, such as and converts the correct ones for the user to and removes all of the others.


The below function currently works but requires me to use note_tags = '.*?\r\n' because the tag group 0 finds all of the tags regardless of whether the user's nickname is in there. So curious how I would use the groups so that I can remove all of the un-useful tags without having to modify the 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)


asked 33 secs ago







Modifying a group within Regular Expression Match

Aucun commentaire:

Enregistrer un commentaire