redhotpenguin has asked for the wisdom of the Perl Monks concerning the following question:
Esteemed Monks,
While my regex tuits have been getting better, I'm faced with a challenge which is throwing me for a loop. I'm trying to extract values from a string (maybe a regex isn't the right way to do this).
The data I'm trying to parse:my $string = <<STRING; A Title What: A description of what it is Date added: January 16th, 2006 ( an optional source ) Data: some data Another Title What: Another description Date added: April 20th, 2005 Data: some other data STRING
I can parse most of this, but what I need to do is assign a default value for ( an optional source ) if the optional source is missing (the default value would be ''. Here's what I have so far:
my @fizzbin = ( $string =~ m{ (\w+)\n # Grab the title What:\s+([^\n]+)\n # Grab the what Date\sadded:\s+([^\(^\n]+) # Date added (\([^\n]+\))\n # Optional source # I want to use a default # value if nothing is # captured Data:\s+([^\n]+)\n # Grab the data }xmgs);
This regex works fine if I don't try to grab the optional source, it returns an array which is not ideal but provides the data I'm looking for ( $title1, $what1, $date1, $data1, $title2, $what2...) I don't know how to assign a default value to the source capture - any advice on that appreciated, including alternate methods of parsing here.
Thanks in advance.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Default value for capture in regular expression
by ikegami (Patriarch) on Jan 16, 2006 at 20:55 UTC | |
|
Re: Default value for capture in regular expression
by ww (Archbishop) on Jan 16, 2006 at 20:47 UTC | |
|
Re: Default value for capture in regular expression
by bmcnett (Novice) on Jan 17, 2006 at 04:19 UTC | |
|
Re: Default value for capture in regular expression
by blazar (Canon) on Jan 17, 2006 at 08:45 UTC |