while( /foo(.*?)(tar)?bar/g ) { next unless $2; ... }