regular expression negate a word (not character)

Greg Bacon gbacon at hiwaay.net
Mon Jan 28 13:53:42 EST 2008


The code below at least passes your tests.

Hope it helps,
Greg

#! /usr/bin/perl

use warnings;
use strict;

use constant {
  MATCH    => 1,
  NO_MATCH => 0,
};

my @tests = (
  [ "winter tire",                => MATCH ],
  [ "tire",                       => MATCH ],
  [ "retire",                     => MATCH ],
  [ "tired",                      => MATCH ],
  [ "snowbird tire",              => MATCH ],
  [ "tired on a snow day",        => MATCH ],
  [ "snow tire and regular tire", => MATCH ],
  [ " tire"                       => MATCH ],
  [ "snow tire"                   => NO_MATCH ],
  [ "snow   tire"                 => NO_MATCH ],
  [ "some snowtires"              => NO_MATCH ],
);

my $not_snow_tire = qr/
  ^ \s* tire |
  ([^w\s]|[^o]w|[^n]ow|[^s]now)\s*tire
/xi;

my $fail;
for (@tests) {
  my($str,$want) = @$_;
  my $got = $str =~ /$not_snow_tire/;
  my $pass = !!$want == !!$got;

  print "$str: ", ($pass ? "PASS" : "FAIL"), "\n";

  ++$fail unless $pass;
}

print "\n", (!$fail ? "PASS" : "FAIL"), "\n";

__END__

-- 
 ... all these cries of having 'abolished slavery,' of having 'preserved the
union,' of establishing a 'government by consent,' and of 'maintaining the
national honor' are all gross, shameless, transparent cheats -- so trans-
parent that they ought to deceive no one.  -- Lysander Spooner, "No Treason"



More information about the Python-list mailing list