#!/usr/bin/perl -l use strict; use warnings; my @str = split /\n/, <<'HTML'; Security Code Matchedfoo Security Code MatchedN/A Security Code MatchedN/A Security Code Matched10! Security Code MatchedN/A HTML for (@str) { if ( m{ \bSecurity\ Code\ Matched\b (.*?) (?(?{ index($^N, 'N/A') < 0 })!) }xsg ) { print "[[$_]]"; } }