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.


In reply to Default value for capture in regular expression by redhotpenguin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.