我如何将一个字符串分解成一个数组由逗号而忽略双引号中的逗号? [英] How do I split a string into an array by comma but ignore commas inside double quotes?

查看:334
本文介绍了我如何将一个字符串分解成一个数组由逗号而忽略双引号中的逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个行:

$string = 'Paul,12,"soccer,baseball,hockey",white';

我尝试这个分割成有4个值,所以

I am try to split this into @array that has 4 values so

print $array[2];

给出


soccer,baseball,hockey

我如何呢?救命啊!

How do I this? Help!

推荐答案

在回应如何与文字:: CSV(_pp)做到这一点。下面是一个简单的。

In response to how to do it with Text::CSV(_PP). Here is a quick one.

#!/usr/bin/perl

use strict;
use warnings;

use Text::CSV_PP;
my $parser = Text::CSV_PP->new();

my $string = "Paul,12,\"soccer,baseball,hockey\",white";

$parser->parse($string);
my @fields = $parser->fields();

print "$_\n" for @fields;

通常情况下人们会安装文字:: CSV 正文:: CSV_PP 通过 CPAN 工具。

要解决的不是能够安装模块,我建议你使用纯Perl的实现,这样就可以安装了。上面的例子会工作假设你复制文本:: CSV_PP 源文本在同一目录作为脚本文本创建了一个名为文件夹名为 CSV_PP.pm 文件。你也可以把它放在其他位置,并使用使用的lib'目录'方法,讨论previously。见<一href=\"http://stackoverflow.com/questions/251705/how-can-i-use-a-new-perl-module-without-install-permissions\">here这里 的看其他方式来解决使用CPAN模块安装的限制。

To work around your not being able to install modules, I suggest you use the 'pure Perl' implementation so that you can 'install' it. The above example would work assuming you copied the text of Text::CSV_PP source into a file named CSV_PP.pm in a folder called Text created in the same directory as your script. You could also put it in some other location and use the use lib 'directory' method as discussed previously. See here and here to see other ways to get around install restriction using CPAN modules.

这篇关于我如何将一个字符串分解成一个数组由逗号而忽略双引号中的逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆