Hi Monks,

Would someone kindly explain why this regex is behaving as it does, and by that I mean why it stops after a word with a trailing ',' and not after a word with a trailing \s? It strikes me that this quantified group of words with a '+' repeat, ...( (\w+[.,;\s]?)+ ) /x; should continue to the end of the string and not stop after the first comma. I need to understand how to stop it at that first comma, (it stops when it should not) as well as how to let it run on to some other anchor. What am I missing?

use v5.20; my $s = "The zip code 94563 is for the city of Orinda, which is in Con +tra Costa County, California."; say "$s"; my ($zip, $words) = $s =~ m/ (\d+) \s+ ( (\w+[.,;\s]?)+ ) /x; say "$zip $words"; say "$1 $2";

On my macOS machine that snippet yields:

The zip code 94563 is for the city of Orinda, which is in Contra Costa + County, California. 94563 is for the city of Orinda, 94563 is for the city of Orinda,

This is a simple string example, but I am working on multi-line 'here' documents that are much larger but contain similar \d+ and \w+ constructions.

Thanks for your help.


In reply to Regex capture group with + repeat by perlboy_emeritus

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.