Search code examples
regexperlack

ack - search for multiple patterns (logical AND)


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?


Solution

  •  /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