Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ack - search for multiple patterns (logical AND)

Tags:

regex

perl

ack

How to search file with the ack to find lines containing ALL (nor any) of defined patterns?

the ANY (OR) is easy, like:

ack 'pattern1|pattern2|pattern3'

but how to write the AND (ALL) ? e.g. how to write the following:

if( $line =~ /pattern1/ && $line =~ /pattern2/ && $line =~ /pattern3/ ) {
    say $line
}

using ack?

Or more precisely, is possible create an regex with logical and?

like image 547
cajwine Avatar asked Mar 28 '16 16:03

cajwine


1 Answers

 /foo/s && /bar/s && /baz/s

can be written as

 /^(?=.*?foo)(?=.*?bar)(?=.*?baz)/s

We don't actually need a look ahead for the last one.

 /^(?=.*?foo)(?=.*?bar).*?baz/s

And since we don't care which instance of the pattern is matched if there are more than one, we can simplify that to

 /^(?=.*foo)(?=.*bar).*baz/s
like image 150
ikegami Avatar answered Sep 28 '22 08:09

ikegami