Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex Query 1

Status
Not open for further replies.

webpager

Programmer
Mar 27, 2001
166
GB
Hi guys
I want to match whole words in a var ($CHECK_CODE)

Matching the string 'is' in the following
"This is a question"
I want to match the 'is' but not the 'i' and 's' in the word 'this'.
My reference book suggests the following but it matches every instance of 'i' and 's' together.

if($CHECK_CODE =~ /(\b$WHAT\b)/){
........ process
}
Where am I going wrong?
thnx
Keith
 
The following works for me.
Code:
#!perl
use strict;

my $CHECK_CODE = "This is a question";
my $WHAT = "is";

if($CHECK_CODE =~ /(\b$WHAT\b)/){
    print qq(matches "$1"\n);
} else {
    print "no match\n";
}
Dont' think I could say where you're going wrong without seeing some more code.
 
Thnanks for the reply
I left out the var. assignment but you understood what I was lookimg for.
Your code appears the samne as my own, unles I have missed something vital. The problem is this:-
I am searching a database for instances of a certain phrase but I am matching more than I would like to.
A good example is searching for the word 'plug'.
The search matches 'plug' but also matches 'plugs'.
I want to match the whole word only and reject the match when it is part of a longer word.
The site is :-If any one would like to see the search in action.
Thanks
keith
 
How are you searching the database? I don't think the code you've shown here is the whole story.
 
if more 'proof' is needed from mikevh's reply this prints the match BEFORE, the actual match ($1) and the match AFTER:-

my $CHECK_CODE = "This is a question";
my $WHAT = "is";
if($CHECK_CODE =~ /(\b$WHAT\b)/){
    print qq(matches "$` |$1| $'"\n);
} else {
    print "no match\n";
}


Kind Regards
Duncan
 
I've used your search engine and I noticed something, you might want to change the title of the page.

---------------------------------------
If you helped... thx.
 
I use regexs extensively and don't really trust the action of "\b". I use (^|[^a-z])$searchstring($|[^a-z]) to look for whole words. This will give you every instance of your string where it is next to beginning of line, end of line, or next to a non-alpha character. It's a little long winded but the outcome is predictable.

Cheers,

Sloppyhack
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top