简体   繁体   中英

Need help with regex to extract strings from data into a hash [perl]

I have a chunk of data from which I need to extract some strings and put them into a hash. Would appreciate your help. I tried to do this with split command but it became too complicated. Below is the example of what I would like help with.

 junk here
        name="bobby"
        team="orange"
    junk here
        name="steve"
        team="blue"
    junk here    
        name="joe"
        team="blue" 
junk here

Need to filter out junk from data. data->regex filter->hash

Hash I want: %hash= ('bobby' => 'orange', 'steve' => 'blue', 'joe' => 'blue',);

Well, assuming your values never contain quotes or any form of escaping, and name= is always the first thing on a line (except leading whitespace):

my %hash;

while ($string =~ /^\s*name="([^"]*)"\s*team="([^"]*)"/mg) {
  $hash{$1} = $2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM