简体   繁体   中英

How do I extract words from a comma-delimited string in Perl?

I have a line:

$myline = 'ca,cb,cc,cd,ce';

I need to match ca into $1 , cb into $2 , etc..

Unfortunately

$myline =~ /(?:(\w+),?)+/;

doesn't work. With pcretest it only matches 'ce' into $1. How to do it right?
Do I need to put it into the while loop?

Why not use the split function :

@parts = split(/,/,$myline);

split splits a string into a list of strings using the regular expression you supply as a separator.

使用my @parts = split(/,/, $myline)不是更容易吗?

Although split is a good way to solve your problem, a capturing regex in list context also works well. It's useful to know about both approaches.

my $line = 'ca,cb,cc,cd,ce';
my @words = $line =~ /(\w+)/g;

Look into the CSV PM's you can download from CPAN, ie Text::CSV or Text::CSV_XS .

This will get you what you need and also account for any comma seperated values that happen to be quoted.

Using these modules make it easy to split the data out and parse through it...

For example:

my @field = $csv->fields;

If the number of elements is variable, then you're not going to do it in the way you're aiming for. Loop through the string using the global flag:

while($myline =~ /(\w+)\b/g) {
    # do something with $1
}

I am going to guess that your real data is more complex than 'ca,cb,cc,cd,ce', however if it isn't then the use of regular expressions probably isn't warranted. You'd be better off splitting the string on the delimiting character:

my @things = split ',', $myline;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM