문제

I'm trying to get the content that was replaced (actually, removed) from the substitution function.

For example:

my $line = q{hello "my" friend "how" are 'you'};
$line =~ s/("[^"]*"|'[^']*')//g; # Removing any balanced quotes

# I'd like to print
# "my" "how" 'you'

Please be kind, I'm beginning with Perl :-).

도움이 되었습니까?

해결책

You can use /e regex modifier to execute code in substitution part, where $1 is being pushed into @w array, and finally replaced by "" empty string.

my @w;
$line =~ s/("[^"]*"|'[^']*')/ push @w,$1; "" /ge;

print "$_\n" for @w;

다른 팁

Instead of doing a global substitute, you can use a loop and process each substitution:

my $line = qq(hello "my" friend "how" are 'you');
print "$1\n" while $line =~ s/("[^"]*"|'[^']*')//;
print "$line\n";

Gives:

"my"
"how"
'you'
hello  friend  are 

Here's another way, using the built-in @- and @+ arrays that hold the offsets of the latest successful match and captures.

It simply finds all the matching substrings, saves them in @removed and deletes them using substr.

use strict;
use warnings;

my $line = q{hello "my" friend "how" are 'you'};

my @removed;

while ($line =~ /("[^"]*"|'[^']*')/g) {
  push @removed, $1;
  substr $line, $-[0], $+[0] - $-[0], '';
}

print $line, "\n";
print "@removed\n";

output

hello  friend  are 
"my" "how" 'you'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top