#!/usr/bin/env perl use v5.10; use strict; use warnings; my $space_edge = qr{ (?(?<= \S) # if there is a nonspace character left (?! \S) # then there must be no space character right | (?= \S) # else there must be a space character right ) }x; while () { my $edges = 0; for my $str ( "foo", "()" ) { my $qstr = quotemeta($str); unless (/$qstr/) { #print "MISSING $str in: $_"; next; } if (/${space_edge}${qstr}/) { $edges++; print "$str EDGE LEFT: $_" } if (/${qstr}${space_edge}/) { $edges++; print "$str EDGE RIGHT: $_" } unless ($edges) { print "$str UNEDGED: $_"; } } } exit; __END__ Put your foo in your pocket. Put your foo() in your pocket. Good food was had by all. What fools these mortals be! food is good to have. That's a major snafoo there. That's a major snafoo. That's a major snafoo That's a major snafoo()zle That's a major snafoo() there. That's a major snafoo()