perlboy_emeritus has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regex capture group with + repeat
by haukex (Archbishop) on Dec 23, 2019 at 06:47 UTC | |
|
Re: Regex capture group with + repeat
by Anonymous Monk on Dec 23, 2019 at 08:10 UTC |