1

我正在尝试解析以下字符串-

输入:"1"|"abc xyz"||"a|25|30"|2345

输出:

"1"
"abc xyz"

"a|25|30"
2345

我怎样才能做到这一点?

4

3 回答 3

5
#!perl
use strict;
use warnings;
use Text::CSV;

my $in = q{"1"|"abc xyz"||"a|25|30"|2345};
my $csv = Text::CSV->new({ sep_char => '|', quote_char => '"' });
$csv->parse($in);
print $_, "\n" for $csv->fields;

输出:

1
abc xyz

a|25|30
2345
于 2012-05-09T03:54:46.650 回答
1

CSV 解析器删除引号。这些解决方案使它们保持完整。

use Text::ParseWords qw(quotewords);
quotewords(qr'[|]', qr("), q("1"|"abc xyz"||"a|25|30"|2345));
# (
#     '"1"',
#     '"abc xyz"',
#     '',
#     '"a|25|30"',
#     2345
# )

use Data::Record qw();
use Regexp::Common qw(delimited);
my $r = Data::Record->new({ split => qr'[|]', unless => $RE{quoted} });
$r->records(q("1"|"abc xyz"||"a|25|30"|2345));
# (
#     '"1"',
#     '"abc xyz"',
#     '',
#     '"a|25|30"',
#     2345
# )
于 2012-05-09T07:03:56.177 回答
0
use strict;
use warnings;

my $input = q{"1"|"abc xyz"||"a|25|30"|2345||"2"|"z|6|7"|"jkl"||b};
print $& eq '||' ? "\n" : "$&\n" while $input =~ /".*?"|\w+|\|.{0}\|/g;

输出

"1"
"abc xyz"

"a|25|30"
2345

"2"
"z|6|7"
"jkl"

b
于 2012-05-09T05:59:30.367 回答