I want to run a sub re process using compile. I have the sub logic working (see the first example below), so that the function prints ", peanut, " as desired. Basically the sub takes emphasis html tags of any length with or without attributes and replaces with ", ". However, I want to get the second version working, which although more verbose is easier to modify because to add a new emphasis tag I add "tagname" instead of "|tagname|/tagname" for the open and close versions respectively. I know the answer is using compile somehow. I searched and could not find the answer.
Works:
def cut_out_emphasis():
str1 = "<b class='boldclass'>peanut</b>
str1 = re.sub(r'<(b|\/b|i|\/i|ul|\/ul)[^>]*>', ', ', str1, flags=re.I)
print str1
Doesn't work:
def cut_out_emphasis():
str1 = "<b class='boldclass'>peanut</b>
list1 = ["b", "i", "ul"]
str2 = ""
for x in list1:
str2 = '%s|%s|/%s' % (str2, x, x)
str2 = "r'<(%s)[^>]*>'" % (str2, )
str1 = re.sub(re.compile(str2, re.IGNORECASE), ', ', str1, flags=re.I)
print str1