Alex Rivera | Logout

Removing html image tags and everything in between from a string

Asked 2012-05-07T17:01:22.383
10

I've seen a number of questions about removing HTML tags from strings, but I'm still a bit unclear on how my specific case should be handled.

I've seen that many posts advise against using regular expressions to handle HTML, but I suspect my case may warrant judicious circumvention of this rule.

I'm trying to parse PDF files and I've successfully managed to convert each page from my sample PDF file into a string of UTF-32 text. When images appear, an HTML-style tag is inserted which contains the name and location of the image (which is saved elsewhere).

In a separate portion of my app, I need to get rid of these image tags. Because we're only dealing with image tags, I suspect the use of a regex may be warranted.

My question is twofold:

  1. Should I use a regex to remove these tags, or should I still use an HTML parsing module such as BeautifulSoup?
  2. Which regex or BeautifulSoup construct should I use? In other words, how should I code this?

For clarity, the tags are structured as <img src="/path/to/file"/>

Thanks!

Edit
Report

1 Answer

15

I would vote that in your case it is acceptable to use a regular expression. Something like this should work:

def remove_html_tags(data):
    p = re.compile(r'<.*?>')
    return p.sub('', data)

I found that snippet here (http://love-python.blogspot.com/2008/07/strip-html-tags-using-python.html)

edit: version which will only remove things of the form <img .... />:

def remove_img_tags(data):
    p = re.compile(r'<img.*?/>')
    return p.sub('', data)
answered 2012-05-07T17:20:15.773

Your Answer