habibrahman_h has asked for the wisdom of the Perl Monks concerning the following question:

All,
I have a problem in regex.. I want only the whole word matched with whole word. There is the following string
"George Best is Alive and Kicking"

The following are the user inputs and they should be matched with above string.
E.g. 1 -> Kicking -->
Only this should return TRUE
E.g. 2 -> Kick --> This should return FALSE but Kick gets matched as the regex returns true (i.e. value) even if a part of the word is matched..

Any solution. Advance Thanks for your help.
Regards, Habib

Replies are listed 'Best First'.
Re: Match Whole Word
by gellyfish (Monsignor) on Jun 06, 2006 at 14:36 UTC

    Read about the \b word boundary regular expression metacharacter in perlre.

    /J\

Re: Match Whole Word
by artist (Parson) on Jun 06, 2006 at 14:52 UTC
    $word = 'Kicking'; $string = 'George Best is Alive and Kicking' ; if ($string =~ /\b$word\b/){ print "TRUE"; }
    --Artist
Re: Match Whole Word
by GrandFather (Saint) on Jun 06, 2006 at 19:01 UTC

    Show us your code. As suggested \b is probably the "answer", but I suspect there is more going on here and that there may be more fundamental stuff you could use some help with.

    At the very least show us the regex you are using at the moment. It may be that something like the following is a better solution:

    use strict; use warnings; my @userWords = qw(kicking kick); my %words = map {chomp; lc $_ => 0} split ' ', <DATA>; exists $words{lc $_} && $words{$_} >= 0 ? ++$words{$_} : --$words{$_} for @userWords; for (sort keys %words) { next if ! $words{$_}; print "not " if $words{$_} < 0; print "found $_\n"; } __DATA__ George Best is Alive and Kicking

    Prints:

    not found kick found kicking

    DWIM is Perl's answer to Gödel