The issue is white space. If the string is as follows:

my $string = "a *test* b";

With the regexp, /\b\*test\*\b/ you get a failure because the junction between a space character and an asterisk (\*) is not a word boundry, because neither space nor \* is a word character (\w). You need to rearrange the regexp one of a couple of ways, depending on what you're trying to accomplish:

m/\b\s\*test\*\s\b/; or m/\*\btest\b\*/;
However, the second example doesn't need the \b, because it is implicit in the fact that you're already specifying non-word characters (*) that must preceed and follow the literal word characters of 'test'.

The first example (probably what you really should be using) says, match where a word has just ended, followed by a space, followed by *test*, followed by a space, followed by a word beginning. That's what the \b is doing for you. Of course \b is a zero width assertion, so you haven't actually matched what comes before the first \b or what comes after the second \b, you're just asserting that there must be a word there.

Note, I used \s to indicate space, but if you want to use an actual space (ascii 32), put a space in your regexp, or spell it out with its ascii value. I used \s so that the whitespace would be clearly visible in reading the regexp.

Hope this helps...

Dave

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


In reply to Re: regex question by davido
in thread regex question by Anonymous Monk

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.