Perl:如何在一个不带引号的字符实例上拆分字符串

时间:2015-07-02 10:23:17

标签: perl split

在perl中,如何仅沿着不带引号的分隔符拆分字符串?即以下字符串:

RewriteRule  ^([a-zA-Z0-9\-\_]+)?$  product.php?product=$1    [NC,L]

应该生成一个包含元素的数组:

my $line = '"a quoted, comma", word1, word2';

2 个答案:

答案 0 :(得分:7)

您可以使用Text::ParseWordsparse_line()

use  Text::ParseWords;

my $line = '"a quoted, comma", word1, word2';

my @parsed = parse_line(',', 1, $line);

# print "@parsed\n"; # this will print in single line

# To print in new line
foreach (@parsed)
{
    print "$_\n";
}

输出:

"a quoted, comma"
 word1
 word2

答案 1 :(得分:2)

您可以使用简单的备用正则表达式

来完成此操作
use strict;
use warnings;
use 5.010;

my $line = q<"a quoted, comma", word1, word2>;

my @words = $line =~ / (?: "[^"]*" | [^,] )+ /xg;

say for @words;

输出

"a quoted, comma"
 word1
 word2