Your problem seems to be that "to" matches "to" and "totally" and "tonight", etc., when you really only want it to match "to".
The key is to tell the regexp engine that you want to match "to" only when it occurs on a word boundry. In fact, you want a word boundry at both sides of it.
Word boundries are zero-width assertions. They don't 'match' anything in particular, but they assert that matches can only occur if the assertion's criteria are met.
The criteria that the '\b' assertion requires is that there be a transition between a \w character and a \W (nonword) character.
Here is an example:
With the \b assertions you only match twice. Once on the "to" that is part of "to's" and the other time on the literal word "to".my $string = "Tonight too many to's were used to explain."; my (@matches) = $string =~ /\b(to)\b/g; print($_,"\n") foreach @matches;
Without the \b assertions, you would match four times: "to"night, "to"o, "to"'s, "to".
Dave
In reply to Re: word matching
by davido
in thread word matching
by TheDoc
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |