in reply to How do I reference repeated capture groups?
G'day TIOOWTDI,
Welcome to the Monastery.
You actually want to capture zero or more instances of '(\s*\d+\s*)'; i.e. '((?:\s*\d+\s*)*)'.
Your OP code:
$ perl -E ' my $re = qr{(\w+)(\s*\d+\s*)*}; my $str = "a 1 2 3 b 4 5 6"; while ($str =~ /$re/g) { say "$&: $1 $2"; } ' a 1 2 3 : a 3 b 4 5 6: b 6
With fixed regex:
$ perl -E ' my $re = qr{(\w+)((?:\s*\d+\s*)*)}; my $str = "a 1 2 3 b 4 5 6"; while ($str =~ /$re/g) { say "$&: $1 $2"; } ' a 1 2 3 : a 1 2 3 b 4 5 6: b 4 5 6
Named captures don't change the regex logic. The start of capture groups changes from '(' to '(?<name>'; and, accessing values changes from '$N' to '$+{name}'.
$ perl -E ' my $re = qr{(?<letter>\w+)(?<digit>(?:\s*\d+\s*)*)}; my $str = "a 1 2 3 b 4 5 6"; while ($str =~ /$re/g) { say "$&: $+{letter} $+{digit}"; } ' a 1 2 3 : a 1 2 3 b 4 5 6: b 4 5 6
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How do I reference repeated capture groups?
by kcott (Archbishop) on Aug 13, 2022 at 03:03 UTC | |
|
Re^2: How do I reference repeated capture groups?
by Anonymous Monk on Aug 13, 2022 at 20:08 UTC |