Forum Moderators: coopster & phranque

Message Too Old, No Replies

Regular Expression problem

Help me with this. Shouldn't be too hard but having brain lock today

         

JerryOdom

5:04 pm on Dec 2, 2004 (gmt 0)

10+ Year Member



I want to compare a word to a list of words stored in a string in a single regular expression and if its equal to any of them exactly then I want it to return positive. The logic should read something like this:

$word = "alphabet";
$string = "and她r在ut安ith地";

if($word!~ /$string/){
#do whatever
}

As you see the problem is that the 'a' will match any word with an 'a' where as I just want it to match 'a' if word is equal to 'a' exactly. I'd like to do this without looping through to test the word against each individually with eq if possible.

Thanks in advance,
Jerry

moltar

6:56 pm on Dec 2, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This should do it:

$word = "alphabet";
$string = "and她r在ut安ith地lphfabet地";

if ( $string =~ /\b\Q$word\E\b/ ) {
## we got a match
}

  • \b
    Searched for word boundaries.
    \b
    is the place between a
    \w
    character and a
    \W
    character.

  • \Q
    and
    \E
    allow to use variables between them. Otherwise Perl will literaly look for a dollar sign followed by 'word'.

Suggest to read: Perl Regex - a tiny introduction [anaesthetist.com]

JerryOdom

9:57 pm on Dec 2, 2004 (gmt 0)

10+ Year Member



Thanks moltar. That link is excellent and the code snippet worked.