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

Dear Monks

I need to match entire words in strings. Words may or may not include an hyphen. Why is the following not working?

$mystring =~/\b($query)\b/i

Replies are listed 'Best First'.
Re: Regex hyphen
by GrandFather (Saint) on Nov 25, 2014 at 10:34 UTC

    what does $query contain? Best would be if you show us a complete script that demonstrates the problem you are having. I'd imagine you should only need half a dozen lines including print statements and initialisation to set variable values.

    Update: using your "context":

    use strict; use warnings; my $mystring = "This is a non-sense sentence."; my $query = "non-sense"; print $mystring =~/\b($query)\b/i ? "Matched" : "Missed";

    prints Matched as expected. Again, please supply a small script (like the one above) that demonstrates the problem.

    Note that there are several flavours of hyphen depending on the character set you are using. Maybe the hyphens in the two strings are actually different characters?

    Perl is the programming world's equivalent of English
Re: Regex hyphen
by Eily (Monsignor) on Nov 25, 2014 at 11:01 UTC

    If you want to find a substring inside a string, index might be a better choice than a regex (because you don't have to compile the regex, it's probably clearer to other people, and there's less unexpected side effects like metachars):

    $string = "This is a non-SENSE sentence"; $substring = "non-sense"; print "Match!" if index(lc $string, lc $substring) >= 0;

Re: Regex hyphen
by Anonymous Monk on Nov 25, 2014 at 12:11 UTC

    Thank you for your suggestions. It was an encoding problem which caused the Regexp not to work. Thank you also for the Index solution, it works very fine too

Re: Regex hyphen
by Anonymous Monk on Nov 25, 2014 at 10:34 UTC

    Some for context

    $mystring="This is a non-sense sentence."; $query="non-sense";