Split line with perl

前端 未结 5 685
深忆病人
深忆病人 2021-01-23 03:57
   title: Football team: Real Madrid stadium: Santiago Bernabeu players: Zinédine Zidane, Ronaldo, Luís Figo, Roberto Carlos, Raúl personnel: José Mourinho (head coach)          


        
5条回答
  •  渐次进展
    2021-01-23 04:28

    Contrary to what many are saying in their answers, you do not need lookahead (other than the Regex's own), you would only need to capture part of the delimiter, like so:

    my @hash_fields = grep { length; } split /\s*(\w+):\s*/;
    

    My full solution below:

    my %handlers
        = ( players   => sub { return [ grep { length; } split /\s*,\s*/, shift ]; }
          , personnel => sub { 
                my $value = shift;
                my %personnel;
                # Using recursive regex for nested parens
                while ( $value =~ m/([^(]*)([(](?:[^()]+|(?2))*[)])/g ) {
                    my ( $name, $role ) = ( $1, $2 );
                    $role =~ s/^\s*[(]\s*//;
                    $role =~ s/\s*[)]\s*$//;
                    $name =~ s/^\s+//;
                    $name =~ s/\s+$//;
                    $personnel{ $role } = $name;
                }
                return \%personnel;
            }
          );
    my %hash = grep { length; } split /(?:^|\s+)(\w+):\s+/, ;
    foreach my $field ( keys %handlers ) { 
        $hash{ $field } = $handlers{ $field }->( $hash{ $field } );
    }
    

    Dump looks like this:

    %hash: {
         personnel => {
                        'assistant coach (es)' => 'Aitor Karanka',
                        'head coach' => 'José Mourinho'
                      },
         players => [
                      'Zinédine Zidane',
                      'Ronaldo',
                      'Luís Figo',
                      'Roberto Carlos',
                      'Raúl'
                    ],
         stadium => 'Santiago Bernabeu',
         team => 'Real Madrid',
         title => 'Football'
       }
    

提交回复
热议问题