您可以指定替换中的每个字段:
#! /usr/bin/env perl
use warnings;
use strict;
use feature qw(say);
for my $line ( <DATA> ) {
chomp $line;
$line =~ s/^\s*(\S+)\s*, # Things: trim off the spaces
(.+?), # ID: Leave alone
\s*(\S+)\s*, # Hello Field: trim off spaces
\s*(\S+)\s* # More things: trim off spaces
/$1,$2,$3,$4/x;
say $line;
}
__DATA__
things,ID,hello_field,more things
stuff,123 ,hello ,more stuff
stuff,123 ,hello ,more stuff
stuff ,123 ,hello ,more stuff
stuff,123 ,hello ,more stuff
stuff ,123,hello ,more stuff
stuff,123,hello ,more stuff
stuff ,123,hello ,more stuff
在这里,我在正则表达式的末尾使用了x,它允许我将表达式分成多行。
这会产生:
things,ID,hello_field,morethings
stuff,123 ,hello,morestuff
stuff,123 ,hello,morestuff
stuff,123 ,hello,morestuff
stuff,123 ,hello,morestuff
stuff,123,hello,morestuff
stuff,123,hello,morestuff
stuff,123,hello,morestuff
我正在考虑使用命名捕获组。如果您要四处移动并且有很多捕获组,它们会很好。但是,在这种情况下,我认为它不会让事情变得更容易阅读:
#! /usr/bin/env perl
use warnings;
use strict;
use feature qw(say);
for my $line ( <DATA> ) {
chomp $line;
$line =~ s/^\s*(?<things>\S+)\s*, # Things: trim off the spaces
(?<id>.+?), # ID: Leave alone
\s*(?<hello_field>\S+)\s*, # Hello Field: trim off spaces
\s*(?<more_things>\S+)\s* # More things: trim off spaces
/$+{things},$+{id},$+{hello_field},$+{more_things}/x;
say $line;
}
__DATA__
things,ID,hello_field,more things
stuff,123 ,hello ,more stuff
stuff,123 ,hello ,more stuff
stuff ,123 ,hello ,more stuff
stuff,123 ,hello ,more stuff
stuff ,123,hello ,more stuff
stuff,123,hello ,more stuff
stuff ,123,hello ,more stuff