Skip
Skip

Reputation: 6521

Perl regexp - retrieve all matchings to list and remove them from text

I have a text, where I would like find all matchings
(e.g. every pattern which match /d.g/ )

Those patterns I need in a list and removed from original text.

Operation on: dog and dig where dug in dug should give me: (dog, dig, dug, dug).

The text should change to: and where in

I could do It by passing the text twice, but it would be double work?

Upvotes: 2

Views: 114

Answers (3)

Borodin
Borodin

Reputation: 126722

I would write it like this

use strict;
use warnings;

my $str = 'dog and dig where dug in dug';
my @matches;

push @matches, substr $str, $-[0], $+[0] - $-[0], '' while $str =~ /d.g/g;

print join(', ', @matches), "\n";

print $str, "\n";

output

dog, dig, dug, dug
 and  where  in 

Upvotes: 0

Gilles Quénot
Gilles Quénot

Reputation: 185171

Try doing this :

$_ = 'dog and dig where dug in dug';

(/\b(d.g)\b/) ? push @_, $1 : print "$_ " for split /\s+/;

print "\n\narr:\n", join "\n", @_;

explanations

  • \b is word boundaries
  • (condition) ? 'if true' : 'if false' statement is a ternary operator

Upvotes: 0

Kenosis
Kenosis

Reputation: 6204

Here's another option:

use strict;
use warnings;

my $str = 'dog and dig where dug in dug';
my @matches;

$str =~ s/\b(d.g)\b/push @matches, $1; ''/ge;

print $str, "\n";
print join ', ', @matches;

Output:

 and  where  in 
dog, dig, dug, dug

Upvotes: 3

Related Questions