Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: regex question

by ikegami (Patriarch)
on Sep 02, 2009 at 23:25 UTC ( [id://793048]=note: print w/replies, xml ) Need Help??


in reply to regex question

[ Ignore this post, I missed how you just want a list of the numbers at the end ]

my %value_lkup = ( A => '1000', B => '2000', ); my $pat = '[' . join('', keys %value_lkup) . ']'; s/($pat)/$value_lkup{$1}/g;

or

s/([AB])/ ( ord($1)-ord('A')+1 )*1000 /eg;

Replies are listed 'Best First'.
Re^2: regex question
by markkawika (Monk) on Sep 02, 2009 at 23:34 UTC

    That's actually a really nice way to use a hash to look through a string and replace keys with values.

    You could even generalize it to multi-character keys:

    my %value_lkup = ( A => '1000', B => '2000', CDE => '3000', ); my $pat = '(?:' . join('|', keys %value_lkup) . ')'; s/($pat)/$value_lkup{$1}/g;

      To make it a general solution, you need to add quotemeta and you gotta be careful about ordering if one key can be the the start of another key. And if you're going to add (?:), you might as well use qr//.

      my ($pat) = map qr/$_/, join '|', map quotemeta, sort { length($b) <=> length($a) } keys %value_lkup; my @data = map $value_lkup{$_}, /$pat/g;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://793048]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2024-10-06 22:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The PerlMonks site front end has:





    Results (43 votes). Check out past polls.

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.