user2148703
user2148703

Reputation: 25

Find non-match using regex (multiple lines)

I have a multi-line file from which I'm trying to find if the file has anything other than the regex string.

Ex:

test 1 str
test 2 str
unmatched string

Sample Regex:

/test .* str/

This regex returns true if it finds a match in the above data. However, I want it to return false at the first mismatch. Is that possible? Any suggestions?

Upvotes: 0

Views: 86

Answers (3)

Miller
Miller

Reputation: 35198

Normally one uses $string =~ /PATTERN/ to test if a $string matches a specific regex pattern.

However, one can also test for the negative, or not matching: $string !~ /PATTERN/.

In this case though, I think you can do it even simpler like the following:

use strict;
use warnings;

while (<DATA>) {
    print if ! /test.*str/;
}

__DATA__
test 1 str
test 2 str
unmatched string

Outputs:

unmatched string

Upvotes: 1

Degustaf
Degustaf

Reputation: 2670

use strict;
use warnings;
while(<>)
{
    return 0 unless(/test .* str/);
}
return 1;

Upvotes: 1

Federico Piazza
Federico Piazza

Reputation: 31005

You can use a little trick if you use a regex like this:

^test . str$|(.*)

Working demo

Then grab the content of the capturing group. If the capturing group contains data then you assume that your file doesn't match your need.

enter image description here

Upvotes: 0

Related Questions