http://www.perlmonks.org?node_id=934577


in reply to A regex question

I like the code from roboticus. A slight reformulation is below.

You can capture all of the names from the "match global" in one expression.

For most of my "web scraping" code, very fast performance is not that important. Neither is being super general purpose. If I can write a short regex in 5 minutes that gets me what I want, then I go with it and if the web page changes in a year, then I write another 5 minute regex.

What makes sense in your application has to do with what you are "scraping", how often the page format changes, what the impact of that will be (maybe boss calling you at midnight - or just some thing that you have to get "done this week"). Mileage varies.

There are some very fine HTML parsing modules and they can be used to make much more general solutions. However, I often write one regex to get to a hunk of html that has what I want and then write another regex like below to extract what I want from that hunk of stuff. Write as much code as you need, but don't write more than you have to. And no matter what you do, this HTML stuff is a very "fragile" interface - meaning that your code will break at the whim of the web developer.

#!/usr/bin/perl -w use strict; $/=undef; my $data =<DATA>; $data =~ tr/\n/ /; #turn \n's into spaces my (@names) = $data =~ m/<a[^>]*>(.*?)<\/a>/g; foreach (@names) { print "$_\n"; } =prints Jon.Martinez Mary Jones Rob Oticus Joe Blow =cut __DATA__ <a href="foo">Jon.Martinez</a><li>gabba, gabba, hey!</li><a href=bar>Mary Jones</a><p>Gazebo!</p><a href="baz">Rob Oticus</a><a>Joe Blow</a>