Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby regex, parsing html

Tags:

regex

ruby

I'm trying to parse some returned html (from http://www.google.com/movies?near=37130 )to look for currently playing movies. The pattern I'm trying to match looks like:
<span dir=ltr>Clash of the Titans</span>

Of which there are several in the returned html.

I'm trying get an array of the movie titles with the following command:
titles = listings_html.split(/(<span dir=ltr>).*(<\/span>)/)

But I'm not getting the results I'm expecting. Can anyone see a problem with my approach or regex?

like image 748
danwoods Avatar asked Dec 30 '25 19:12

danwoods


2 Answers

It is considered Verey Bad generally to parse HTML with RegExs since HTML does not have regular grammar. See the list of links to explanations (some from SO) here.

You should instead use a designated HTML library, such as this

like image 189
Alice Avatar answered Jan 01 '26 07:01

Alice


I didn't read the whole code you posted since it burned my eyes.

<span>.*</span>

This regex matches <span>hello</span> correctly, but fails at <span>hello</span><span>there</span> and matches the whole string. Remember that the * operator is greedy, so it will match the longest string possible. You can make it non-greedy by using .*? should make it work.

However, it's not wise to use regular expressions to parse HTML code.

1- You can't always parse HTML with regex. HTML is not regular.

2- It's very hard to write or maintain regex.

3- It's easy to break the regex by using an input like <span><a href="</span>"></a></span>.

like image 38
tiftik Avatar answered Jan 01 '26 09:01

tiftik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!