regexperl

OR condition in regular expression in perl


I am trying to write a script which performs an OR function through regular expressions in Perl. I have written a code in which if string contains 'D' or 'E' followed by 'P' it should print "D or E followed by P" otherwise "D or E not followed by P". Suppose if I give $s = 'ABCDEABCDEPABCDEAB' it should print the else condition but I think my if statement is not working properly. Please help.

my $s = 'ABCDEABCDEPABCDEAB';
if ($s =~ /D|E(?=P)/) {
    print "D or E is followed by P";
} 
else {
    print "D or E is not followed by P";
}

Solution

  • if ($s =~ /[DE]P/) {
        print "D or E is followed by P";
    }
    else {
        print "neither D nor E is followed by P";
    }