Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to match output to a given set of expected output. The matching contains boundary character :
$output =~ /\b$expectedoutput\b/i since I want  abc to be matched to  abc but not to  habcd or  habc or  abcd .
I found out that if there is a forward slash in my expected output then it is not matching even though there may be a backslash in front of it . Example:  $expectedoutput=\/usr\/myname The problem occurs due to the \b (word boundary) that I am using while matching. Is there a way to get these to work together ?
I have full control on what I can put in the expected output so can I modify $expectedoutput somehow to get this scenario to work ?
Thanks.

Replies are listed 'Best First'.
Re: backslash and word boundaries while matching
by ysth (Canon) on Aug 06, 2004 at 20:53 UTC
    The problem is that if there is a space before "/usr/myname" in your string, there isn't a word boundary before the /, but if there is e.g. an "x" ("x/usr/myname"), there is.

    So don't use \b, instead look for no word character before or after: /(?<!\w)$expectedoutput(?!\w)/.

    Update: as Prior Nacre V suggests, you probably want to use \Q around $expectedoutput in case of special regex characters in your variable (e.g. "."), but that won't fix your \b problems.

Re: backslash and word boundaries while matching
by Prior Nacre V (Hermit) on Aug 06, 2004 at 20:53 UTC

    Just wrap it in \Q ... \E:

    $output =~ /\b\Q$expectedoutput\E\b/i

    If $expectedoutput is constant, add an 'o' modifier for efficiency.

    PN5