Counterpart to PHP’s preg_match in Python

funnyguy picture funnyguy · Jan 30, 2012 · Viewed 18.7k times · Source

I am planning to move one of my scrapers to Python. I am comfortable using preg_match and preg_match_all in PHP. I am not finding a suitable function in Python similar to preg_match. Could anyone please help me in doing so?

For example, if I want to get the content between <a class="title" and </a>, I use the following function in PHP:

preg_match_all('/a class="title"(.*?)<\/a>/si',$input,$output);

Whereas in Python I am not able to figure out a similar function.

Answer

RanRag picture RanRag · Jan 30, 2012

You looking for python's re module.

Take a look at re.findall and re.search.

And as you have mentioned you are trying to parse html use html parsers for that. There are a couple of option available in python like lxml or BeautifulSoup.

Take a look at this Why you should not parse html with regex