my $str = "This is a line # with comment"; my $word = '#'; while ($str =~ /[^\B#]($word)[^\B#]/g) { print "$1\n"; } __OUTPUT__ # #### my $str = "This is a line # with comment Boss."; my $word = "#"; # define custom \b my $b = qr/(?:(?=\S)(?