PerlGrepExactMatch

Want to perform an exact match with Perl's grep function?

Perl's grep function is incredibly powerful. However, at first glance it can seem as if Regular Expressions are going to trip you up. For example, if you want to perform an exact match with data that might contain Regualr Expression special characters. For example, this looks like it might be a problem...

my @elements=("apple", "apple.", "apple1", "apple2", "banana");

 my @results=grep(/apple/,@elements);5

Here, @results will contain "apple", "apple.", "apple1" and "apple2". This can or course be avoided as follows:

my @results=grep(/^apple$/,@elements);

Which will only put "apple" into the results. But what if the search term contains metacharacters (like . * ? etc)? For this you need a non-regular expression version of grep. Here's an example:

my @results=grep( { "$_&" eq "apple." } @elements);

Here, @results will only contain "apple.", because it's the only thing that matches exactly. The check is a simple string "eq" rather than a regular expression, so metacharacters aren't used. Rememeber, this won't work:

my @results=grep(/^apple.$/, @elements);

...becuase the "." will match any single character. You'll end up with "apple.", "apple1" and "apple2" in @results.

ALSO SEE: PerlTextSort

Submitted by coofercat on Sun, 2006-02-12 20:18

Comments

match metacharacter

if you are interested only in "apple."
What about the following...

my @results=grep(/^apple\.$/, @elements);

seems simpler than
my @results=grep( { "$_" eq "apple." } @elements);

Submitted by Anonymous (not verified) on Fri, 2006-02-17 17:33.
Re: match metacharacter

Yep, for sure. Indeed, you can use the quotemeta() function to do just that. However, in more complex scenarios, an exact match can be useful.

Submitted by coofercat on Sat, 2006-02-18 00:28.
how about negating the match?

how do i get all occurrences that do not match "john"? i know on the command line you can do grep -vbut how about perl?
Roumen Semov

Submitted by Anonymous (not verified) on Sat, 2006-03-25 01:03.
Re: how about negating the match?

Here you go:
grep !/john/, @array1;
Roumen Semov

Submitted by Anonymous (not verified) on Sat, 2006-03-25 01:29.
Worked

Thank you for this helpful tip.
Mauricio

Submitted by Mauricio (not verified) on Tue, 2010-12-14 23:13.
Powerful

Perl grep is very powerful. I didn't know about Perl Grep until recently and always was using Linux grep to do stuff. Thanks for the tip. Also found this interesting tutorial on perl grep: http://programmingbulls.com/perl-grep

Submitted by Anonymous (not verified) on Wed, 2011-08-10 13:07.
regexp vs eq

my @results=grep(/^apple\.$/, @elements);
This will match any regexp in input, like ? or *, it's dangerous

my @results=grep( { "$_" eq "apple." } @elements);
This one will match only the exact string
Try it..

Submitted by Anonymous Coward (not verified) on Thu, 2011-09-08 10:28.