Errm, jeffa, that woud screw the my ($start,$middle,$end) part up.
Suggested alternatives:
# first one my ($start, $middle, undef, $end) = $string =~ /^(.*?)(($pattern)+)(.* +?)$/g; # second one, with non-capturing parens -- I like it better my ($start,$middle,$end) = $string =~ /^(.*?)((?:$pattern)+)(.*?)$/g;
gri6507, note that /$pattern+/ is exactly the same as /AB+/ (well, at least for $pattern = 'AB'), which is, by definition /A(:?B)+/.
Hope this helped.
CombatSquirrel.

Update: Arghh - wrong order for capturing and non-capturing parens. Fixed.

Update 2: jeffa is right. The following RegEx should do the trick:
$pattern = 'AB'; 'BABABABBB' =~ / ^ # start at beginning of line ( # capture to $1 .*? # a number of character, but as few as possi +ble ... (?<!$pattern) # ... which may not contain $pattern ) ( # capture to $2 (?:$pattern)+ # multiple occurences of $pattern | # OR (?!.*?$pattern) # nothing, BUT there may be no $pattern in t +he rest # of the string ) (.*) # capture rest to $3 /x ; print "$1<$2>$3$/"; __END__ prints "B<ABABAB>BB"
I'm open for any suggestions, and yes, I do know Mastering Regular Expressions, I just forgot half (the important half) of it.

Update 3 (Explanation): The RegEx engine tries to match at the earliest possible position. Therefore it will always match nothing to be captured in $1 (non-greedy dot-star), the highest possible number of following pattern matches (greedy star) and then the rest. Meaning, if the first pattern does not begin at the first character, $2 will also be empty (after all a star does not have to match) and the rest is slurped into $3. Bon appetit!

In reply to Re: Re: Regex help by CombatSquirrel
in thread Regex help by gri6507

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.