ibm1620 has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to capture and remove certain substrings from a string. In this example I want to capture and remove words starting with 'foo', preserving the residual string.
This gives:#!/usr/bin/env perl use v5.36; my $x = "xyzzy foo1 foo2"; my @captured; while ($x =~ s{ \s* (foo\w) \s* }{}msxg) { push @captured, $1; } say "Captured: '$_'" for @captured; say "Left with '$x'";
Removing the 'g' option gives me what I want:Captured: 'foo2' Left with 'xyzzy'
But I'm not clear why the regex 'g' option in a while-loop behaves differently for matching than for substitution.Captured: 'foo1' Captured: 'foo2' Left with 'xyzzy'
Also, I'm wondering if there's a better way to capture and remove a repeated pattern from a string like the above.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: while-loop regex substitution with 'g' option
by ikegami (Patriarch) on Apr 21, 2024 at 20:58 UTC | |
by ibm1620 (Hermit) on Apr 22, 2024 at 04:43 UTC | |
|
Re: while-loop regex substitution with 'g' option
by tybalt89 (Monsignor) on Apr 22, 2024 at 00:31 UTC | |
by ibm1620 (Hermit) on Apr 22, 2024 at 04:55 UTC | |
|
Re: while-loop regex substitution with 'g' option
by LanX (Saint) on Apr 21, 2024 at 19:13 UTC |