Well then, you've got a problem, but I'm going to propose a solution. First, I'll try to explain the problem.

If one label is "Programming Languages:", another label is "Author:", and another is "Date Created:", you clearly cannot count on the labels not having whitespace. And if your data fields are "C++, Java", "John", "2004-01-05 10:23...", you clearly cannot count on your data fields not containing whitespace. Your fields aren't of fixed width either. And your delimiter (the colon) appears mid-record, so it's more of an anchor than a delimiter, which doesn't help tremendously. What that leaves you with is this: No good way of determining where a data field ends, and where a new label starts. ......unless, of course.... unless you're lucky enough to know all the possible labels.

Maybe you could instead skim for known labels. That would be helpful. For example, if you know that the only labels in the text are "Programming Languages", "Author", and "Date Created", you could compose your regular expression like this:

my $labels = qr/Programming Languages|Author|Date Created/; my $re = qr/($labels):(.+?)(?=$labels|$)/; while( my( $label, $data ) = $text =~ m/$re/g ) { print "Label: $label\tData: $data\n"; }

This will capture the known label into $label on each iteration, and then the field following the label into $data. Each match stops as soon as the lookahead assertion finds the next known label, or the end of the string.


Dave


In reply to Re^3: RegEx question by davido
in thread RegEx question by mariuspopovici

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.