Jean
Jean

Reputation: 22695

Perl regex negation

How do I negate this regular expression (without using !~)?

my $Line='pqr_abc_def_ghi_xyz';

if ($Line=~/(?:abc|def|ghi)/)
{
   printf("abc|def|ghi is not present\n");
}
else
{
   printf("abc|def|ghi is present\n");
}

Note: abc,def or ghi could be preceded or succeeded by string

Upvotes: 2

Views: 3259

Answers (3)

user557597
user557597

Reputation:

Another way, this might give you more control of the individual component substrings

 #  (?s)^(?:(?:(?!abc|def|ghi).)+|)$

 (?s)
 ^ 
 (?:
      (?:
           (?!
                abc
             |  def
             |  ghi 
           )
           . 
      )+
   |  
 )
 $

Upvotes: 2

Birei
Birei

Reputation: 36262

Another option could be to use unless instead of if:

unless ($Line=~/(?:abc|def|ghi)/){printf("abc|def|ghi is not present\n");}
else                         {printf("abc|def|ghi is present\n");}

Upvotes: 1

ysth
ysth

Reputation: 98398

if ( $Line =~ /^(?!.*(?:abc|def|ghi))/s ) {

I.e., it is not possible to match that pattern anywhere after the start of the string.

Upvotes: 5

Related Questions