I'm trying to split header names for colums in a datafile. The issue I encountered was awkward formatting. A simple example of this headerline is: 'Iteration {Applied Field} {Total Energy} Mx'

Each element is separated by \s+. However, if the element contains whitespace, it is surrounded with curly brackets. The two patterns I try to match are '\s+{([\s\w:]+)}\s+' and '\s+([\w:]+)\s+' The latter one sometimes overlaps the first ('{blaa blaa blaa}').

I'm looking for guidance how to improve my current solution:

use warnings; use strict; my $str = 'Iteration {Applied Field} {Total Energy} Mx'; while(length($str)>0){ #print "str:$str:\n"; if($str =~ m/^({([\s\w:]+)}(\s+)?)/){ print "1: $2\n"; $str =~ s/^$1//; } elsif($str =~ m/^(([\w:]+)(\s+)?)/){ print "2: $1\n"; $str =~ s/^$1//; } else{die "error";} } Result: 2: Iteration 1: Applied Field 1: Total Energy 2: Mx
i.e. try pattern 1 if it fails, try pattern 2. Then, remove the matching part from the beginning. Is it possible to combine two patterns into normal split function or m/.../g pattern and capture the text from the middle?


In reply to Splitting string using two overlapping patterns by kpr

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.