carol
carol

Reputation: 171

grep a specific strings in a Perl array

How to grep only multiple sets of five characters in any order in an array in a Perl program?

@arr2 = grep(/[BCRZ]+/, @arr1);

@arr1 can contain

CRZBBZTCCBBRZ
FJDLSFJSLFJS
CRZBBZCCBBRZ

only the lines like the last should be taken

Upvotes: 0

Views: 780

Answers (2)

Borodin
Borodin

Reputation: 126722

I think this may do what you want. It rejects a string if it contains any character other than CBRZW.

use strict;
use warnings;

my @arr1 = qw/ CRZBBZTCCBBRZ FJDLSFJSLFJS CRZBBZCCBBRZ /;

my @arr2 = grep { not /[^CBRZW]/ } @arr1;

print "$_\n" for @arr2;

output

CRZBBZCCBBRZ

Upvotes: 3

Len Jaffe
Len Jaffe

Reputation: 3484

If what is you want is lines that only contain the 5 chars and none others, then a regex like:

 /^[BRCZW]+$/

looks for strings containing one or more of your 5-character set, but containing no other characters. But it might be more efficient to us @carol's solution using grep(). Which uses a regex to determine if the string has any of the unwanted characters, and then rejects that line.

Upvotes: 3

Related Questions