in reply to regex only matching from last match
I think that you can do this with line by line processing rather than "slurping all lines into a scalar" and getting "fancy" with the regex.
I don't know what a MARC code is. But, the basic idea here is that we find an ISBN number, then we find the title. Then the search goes on for the next ISBN number skipping all records inbetween. The ISBN number is easy to find and if this MARC code makes a difference, you will see how to adapt the below regex'es.
This type of approach only looks at each input line once. There is no need to put all HTML text into one variable. HTML can have infinitely long lines and is typically not formatted for easy user reading - that is an advantage when we parse it!
The code below uses one of my favorite tricks, NOT using $1, etc!
(my $ISBN = (m/\|a\s+(\d{13})/)[0]); uses list slice to assign
$ISBN right away, eliminating the need for $1.
#!/usr/bin/perl -w use strict; my %Isbn2Title; while (<DATA>) { next unless (my $ISBN = (m/\|a\s+(\d{13})/)[0]); my $title = get_title(); $title =~s/\s+$//; #delete trailing whitespace ${Isbn2Title}{$ISBN}=$title; } foreach my $isbn (sort keys %Isbn2Title) { print "ISBN=$isbn title=$Isbn2Title{$isbn}\n"; } #Prints: ISBN=9780470086223 title=Heads in the sand sub get_title { while (<DATA>) { my $title = (m/\|a\s+(.*?)[\|:]/)[0]; return $title if $title; } } __DATA__ <!-- filename: full-000-body-cdl90 --> <tr> <td class="contentSmall" valign="top" id=bold width="5%" nowrap><str +ong> 020</strong></td> + <td class="contentSmall" valign="top">|a 9780470086223 (hardback)</t +d> </tr> <!-- end: full-000-body-cdl90 --> <!-- filename: full-000-body-cdl90 --> <tr> <td class="contentSmall" valign="top" id=bold width="5%" nowrap><str +ong> 24510</strong></t +d> <td class="contentSmall" valign="top">|a Heads in the sand : |b how +the Republicans screw up foreign policy and foreign policy screws up +the Democrats / |c Matthew Yglesias</td> </tr> <!-- end: full-000-body-cdl90 --> <!-- filename: full-000-body-cdl90 --> <tr> <td class="contentSmall" valign="top" id=bold width="5%" nowrap><str +ong> 24610</strong></t +d> <td class="contentSmall" valign="top">|a How the Republicans screw u +p foreign policy and foreign policy screws up the Democrats</td> </tr> <!-- end: full-000-body-cdl90 --> <!-- filename: full-000-body-cdl90 --> <tr> <td class="contentSmall" valign="top" id=bold width="5%" nowrap><str +ong> 61020</strong></t +d> <td class="contentSmall" valign="top">|a Democratic Party (U.S.)</td +> </tr> <!-- end: full-000-body-cdl90 -->
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: regex only matching from last match
by Foxpond Hollow (Sexton) on Sep 24, 2009 at 16:50 UTC |