Сплит линия с Perl
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) Aitor Karanka (assistant coach (es))
Как разделить это с Perl в:
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) Aitor Karanka (assistant coach (es))
5 ответов
Решение
Используйте опережающее утверждение:
say for split /(?=\w+:)/, $real_madrid_string;
Выход
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) Aitor Karanka (assistant coach (es))
Это должно сделать это. line.txt содержит "title: Футбольная команда: стадион Реал Мадрид: игроки Сантьяго Бернабеу: Зинедин Зидан, Роналду, Луис Фигу, Роберто Карлос, Рауль персонал: Жозе Моуринью (главный тренер) Айтор Каранка (помощник тренера (ов))"
#!/usr/bin/perl
use strict;
use warnings;
my $fn="./line.txt";
open(IN,$fn);
my @lines=<IN>;
my %hash;
my $hashKey;
foreach my $line (@lines){
$line=~s/\n//g;
my @split1=split(" +",$line);
foreach my $split (@split1){
if($split=~m/:$/){
$hashKey=$split;
}else{
if(defined($hash{$hashKey})){
$hash{$hashKey}=$hash{$hashKey}.$split." ";
}else{
$hash{$hashKey}=$split." ";
}
}
}
}
close(IN);
foreach my $key (keys %hash){
print $key.":".$hash{$key}."\n";
}
Вопреки тому, что многие говорят в своих ответах, вам не нужно смотреть в будущее (кроме собственного Regex), вам нужно будет только захватить часть разделителя, например:
my @hash_fields = grep { length; } split /\s*(\w+):\s*/;
Мое полное решение ниже:
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+/, <DATA>;
foreach my $field ( keys %handlers ) {
$hash{ $field } = $handlers{ $field }->( $hash{ $field } );
}
Дамп выглядит так:
%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'
}
$string = "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) Aitor Karanka (assistant coach (es))";
@words = split(' ', $string);
@lines = undef;
@line = shift(@words);
foreach $word (@words)
{
if ($word =~ /:/)
{
push(@lines, join(' ', @line));
@line = undef;
}
else
{
push(@line, $word);
}
}
print join("\n", @lines);
Лучший способ - использовать split
команда с использованием заглядывания нулевой ширины:
$string = "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) Aitor Karanka (assistant coach (es))";
@split_string = split /(?=\b\w+:)/, $string;