Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: matching numeric range

by jimbojones (Friar)
on Feb 24, 2005 at 22:44 UTC ( #434290=note: print w/replies, xml ) Need Help??

in reply to matching numeric range


I think a hash is the answer. Assuming the second 2 elements of your data (delimited by the ':') don't involve the range, you could do something like:

my %checks = ( '123:C' => [ 'A[0-7]' ], '456:D' => [ 'B[8-9]', 'B1[0-5]' ] ); while ( <DATA>) { chomp; my $check = $_; my $matches = 0; #-- get the trailing key my $first_part = ""; my $key = ""; if ( $check =~ /(\w+):(\w+:\w+)$/ ) { $first_part = $1; $key = $2; } #-- look up key in our checks hash foreach my $match_pattern ( @{$checks{$key}} ) { if ( $first_part =~ /$match_pattern/ ) { print "Line $_ matches $match_pattern:$key\n"; $matches = 1; } } print "Line $_ doesn't match\n" unless ( $matches ); } __DATA__ A4:123:C B8:456:D B11:456:D X11:456:D
Line A4:123:C matches A[0-7]:123:C Line B8:456:D matches B[8-9]:456:D Line B11:456:D matches B1[0-5]:456:D Line X11:456:D doesn't match

Replies are listed 'Best First'.
Re^2: matching numeric range
by state-o-dis-array (Hermit) on Feb 24, 2005 at 23:18 UTC
    I'm liking this. One question on this. Is there a simple way (one line regex substitution for example) to get from B10-15 to B1[0-5], or B120-125 to B12[0-5]? Actually, as I think about it, I may need to apply some logic to handle B18-24. Can you think of a good way to handle this one?

      the B10-15 example is easy: B1[0-5] (character class), as is B120-125 (B12[0-5]). As you say, logic spanning B18-24 is more difficult; that's why I broke it into 2 regexs in my post above. It was easier to match B1[8-9] or B2[0-4] than to try some regex-fu. You may be more adept with regexes than I am.

      - j

      update: escape out [ ] so they're visible.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://434290]
[robby_dobby]: "My cat is a very good mouser" -- that's a great way to identify a Brit among a crowd :-)
thezip looks around to see no one else dancing to Piazzola...
[thezip]: Our cat is single-handedly (pawed-ly?) solving our field mouse problem. About four critters in the last week alone.

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (12)
As of 2017-11-17 19:46 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (272 votes). Check out past polls.