use warnings; use strict; use Test::More; my $re = qr{ \b type = "([^"]+)" (?: (?!<\w+TagIwant\b) . )* <(\w+TagIwant\b)? }msx; is_deeply [ q{ } =~$re], ['MyType','SomeTagIwant']; is_deeply [ q{ } =~$re], ['MyType','SomeTagIwant']; is_deeply [ q{ } =~$re], ['MyType','SomeTagIwant']; is_deeply [ q{ } =~$re], ['MyType',undef]; done_testing;