To elaborate on the "word boundry" discussion:

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:

my $string = "Tonight too many to's were used to explain."; my (@matches) = $string =~ /\b(to)\b/g; print($_,"\n") foreach @matches;
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".

Without the \b assertions, you would match four times: "to"night, "to"o, "to"'s, "to".


Dave


"If I had my life to do over again, I'd be a plumber." -- Albert Einstein

In reply to Re: word matching by davido
in thread word matching by TheDoc

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.