Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing XML in Python with regex

Tags:

python

regex

xml

I'm trying to use regex to parse an XML file (in my case this seems the simplest way).

For example a line might be:

line='<City_State>PLAINSBORO, NJ 08536-1906</City_State>'

To access the text for the tag City_State, I'm using:

attr = re.match('>.*<', line)

but nothing is being returned.

Can someone point out what I'm doing wrong?

like image 273
user2671656 Avatar asked Aug 11 '13 04:08

user2671656


2 Answers

You normally don't want to use re.match. Quoting from the docs:

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).

Note:

>>> print re.match('>.*<', line)
None
>>> print re.search('>.*<', line)
<_sre.SRE_Match object at 0x10f666238>
>>> print re.search('>.*<', line).group(0)
>PLAINSBORO, NJ 08536-1906<

Also, why parse XML with regex when you can use something like BeautifulSoup :).

>>> from bs4 import BeautifulSoup as BS
>>> line='<City_State>PLAINSBORO, NJ 08536-1906</City_State>'
>>> soup = BS(line)
>>> print soup.find('city_state').text
PLAINSBORO, NJ 08536-1906
like image 67
TerryA Avatar answered Nov 16 '22 04:11

TerryA


Please, just use an XML parser like ElementTree

>>> from xml.etree import ElementTree as ET
>>> line='<City_State>PLAINSBORO, NJ 08536-1906</City_State>'
>>> ET.fromstring(line).text
'PLAINSBORO, NJ 08536-1906'
like image 9
Viktor Kerkez Avatar answered Nov 16 '22 02:11

Viktor Kerkez