Or if you want to grab all the matches in an array you can:

use strict; use warnings; my $text = "test1 zzzzzzzzzzzzzzz test2 test3 test4 test5 zzzzzzzzzzzz +zzz test6 test7 zzzzzzzzzzzzzzz test8 test9 test10"; my @matches = $text =~ /([a-zA-Z0-9]+\s+[z]{15}\s+[a-z0-9]+)/g; print "string: $_!\n" for @matches;

Prints:

string: test1 zzzzzzzzzzzzzzz test2! string: test5 zzzzzzzzzzzzzzz test6! string: test7 zzzzzzzzzzzzzzz test8!

Note that in this case the regex is evaluated in list context so it generates the list of captures as the result. bobf's version evaluates the regex in scalar context and generates a success/fail result and (because of the /g switch) stops on successive matches until all matches are found. Note that bobf's version retreives the capture text from the capture variable ($1 in this case) whereas the list version gets the captures put into the list. Consider:

... my @cap = $text =~ /([a-zA-Z0-9]+)\s+[z]{15}\s+([a-z0-9]+)/g; while (@cap) { print "string: $cap[0] ... $cap[1]\n"; splice @cap, 0, 2; }

which prints:

string: test1 ... test2 string: test5 ... test6 string: test7 ... test8

Note the two capture groups in the regex now. To generate the output shown in this case bobf's print line would become:

print "string: $1 ... $2\n";

DWIM is Perl's answer to Gödel

In reply to Re: regex question by GrandFather
in thread regex question by goff

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.