lev has asked for the wisdom of the Perl Monks concerning the following question:
$line = "2006-01-01,Kims,Watson,406,560(centrifuge, refrig.),569,607(dark room),210-211,101(ultracentrifuge),104-105(crystal growth rooms),660(centrifuge, refrig.)";
(It is a list of fields separated by commas: date, building,Prof(group), room or lab(function),...)
My object is to extract each field (between commas, outside any parentheses) to separate variables
($1, $2, $3…).
Making progress, slowly, I came to a promising but puzzling point with the regex:
$line =~ m/(\d{4}-\d\d-\d\d),(\w*),(\w*),(\w*,|\w*\(.*?\),?|\w*-\w*,|\w*-\w*\(.*?\),?)*/; #{8} replaces *
This gives me four of the expected 11 variables, the fourth being the last variable of the line. O.K., I understand that the match takes the last of (all|alternative|room|patterns)*, but I would like to have all the fields captured as variables.
When I use {n} in place of the ultimate '*', I get each alternative, ‘room (function)’ field in turn as n = 1 to 8.
Is there a way to catch all variables, i.e. $4 …$11 in one expression (without looping this all through values of n)?
Also, a more minor point, the use of ',?' allows for catching the end variable which alone is not followed by a comma. In the case here with 660(...)as the end variable, using '.?' after a 'room(function)'pattern(\w*(...),?) helps, but after a nondescript 'room'pattern( \w*,?), the match fails. So, in general, not knowing the end variable, how do I account for the commas to assure that the last variable is not lost?
Below is my test program.
#!/usr/local/bin/perl use warnings; use strict; my $line = "2006-01-01,Kims,common,406,560(centrifuge,refrig.),569b,60 +7(dark room),210-211,101(ultracentrifuge),104-105(crystal growth room +s),660(centrifuge,refrig.)"; $line =~ m/(\d{4}-\d\d-\d\d),(\w*),(\w*),(\w*,|\w*\(.*?\),?|\w*-\w*,|\ +w*-\w*\(.*?\),?)*/; #{8} replaces * print "1:$1\n", "2:$2\n","3:$3\n","4:$4\n","5:$5\n","6:$6\n","7:$7\n", +"8:$8\n","9:$9\n","10:$10\n","11:$11\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regular Expression, Catching Variables
by suaveant (Parson) on Jun 23, 2009 at 15:56 UTC | |
by Marshall (Canon) on Jun 23, 2009 at 16:54 UTC | |
by suaveant (Parson) on Jun 24, 2009 at 14:08 UTC | |
by Marshall (Canon) on Jun 26, 2009 at 23:15 UTC | |
|
Re: Regular Expression, Catching Variables
by AnomalousMonk (Archbishop) on Jun 23, 2009 at 19:26 UTC | |
|
Re: Regular Expression, Catching Variables
by locked_user sundialsvc4 (Abbot) on Jun 23, 2009 at 16:19 UTC | |
|
Re: Regular Expression, Catching Variables
by oko1 (Deacon) on Jun 23, 2009 at 17:32 UTC | |
by ack (Deacon) on Jun 23, 2009 at 19:17 UTC | |
|
Re: Regular Expression, Catching Variables
by cdarke (Prior) on Jun 23, 2009 at 15:54 UTC |