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

I would like to find words in a string. I don't want to find substrings of my search words. For example, if I search for india, I do not want indian or indiana. What is the best way to do this? Thanks, mumphis

Replies are listed 'Best First'.
Re: finding whole words in a string
by mrbbking (Hermit) on May 07, 2002 at 18:45 UTC
    Look for word breaks:
    #!/usr/bin/perl -w use strict; foreach (qw(india indian indiana)){ print if /\bindia\b/; }
    HTH - mrbbking
Re: finding whole words in a string
by Kanji (Parson) on May 07, 2002 at 18:51 UTC

    Use a regular expression with the \b assertion (which matches at word boundries) before and after the word you want to match ...

    if ( $text =~ /\bindia\b/ ) { # ... };

        --k.


Re: finding whole words in a string
by hopes (Friar) on May 07, 2002 at 18:45 UTC
    Use the \b This match "the blank" the nothing after and before your word:
    $string =~ /\bindia\b/i;
    (Thanks Fletch)

    Hopes
    $_=$,=q,\,@4O,,s,^$,$\,,s,s,^,b9,s, $_^=q,$\^-]!,,print

      Technically it doesn't match `the blank'. As perlre states it matches at a `\w\W' or '\W\w' transition (it doesn't match anything literally as it's zero width, just at a point where the previous character is \w and the next is \W (or vice versa)).

        Sure Fletch, I was not clear. I would had to say:

        \b matches the nothing after and before ...


        Hopes
        $_=$,=q,\,@4O,,s,^$,$\,,s,s,^,b9,s, $_^=q,$\^-]!,,print
Re: finding whole words in a string
by TexasTess (Beadle) on May 16, 2002 at 00:02 UTC
    append a blank both before and after the search string, then match the find to the string..thus returning only words with leading and trailing blanks after the group of desired characters....