Reputation: 109
I want to delete doubled words from string in Perl, for example i have a string : This is text text text very important and and meaningful simply simply text.
And i do this:
$linia =~ s/(.*)\1/$1/g;
But it only works for two doubled words, how to change to make it for 2+ doubled words.
Upvotes: 1
Views: 67
Reputation: 91428
How about:
my $str = q/abcabcabcabc/;
$str =~ s/(.+?)\1+/$1/;
print $str,"\n";
If you have spaces between words:
my $str = q/abc abc abc abc/;
$str =~ s/(\w+\s+)\1+/$1/g;
Output:
abc
Upvotes: 0
Reputation: 50647
Just add +
to match on or more times,
$linia =~ s/(.*)\1+/$1/g;
or if you want to remove all duplicates,
my %seen;
$linia =~ s|(\w+)| $seen{$1}++ ? "" : $1 |ge;
Upvotes: 1