Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Matching a Word Exactly

by GuiPerl (Acolyte)
on Oct 09, 2014 at 09:13 UTC ( [id://1103274]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Fellows, I was wondering how I can match the word Guinea and not other country names such as Equatorial Guinea, etc.
use strict; use warnings; while (<DATA>) { if ($_ =~ m/\bGuinea\b/) { print "We have a match\n"; # m/\bGuinea\b$/ matches Guinea at end #m/^\bGuinea\b$/ matches Guinea at the beginning } else { print "We do not have a match\n"; } } __DATA__ Papua New Guinea I live in Guinea Guinea Bissau Equatorial Guinea

Replies are listed 'Best First'.
Re: Matching a Word Exactly
by karlgoethebier (Abbot) on Oct 09, 2014 at 11:30 UTC

    BTW, proper indention and omitting unnecessary whitespace isn't a bad thing :-)

    See also Perltidy.

    Best regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

Re: Matching Exact Word
by Anonymous Monk on Oct 09, 2014 at 09:16 UTC
      sleepy i guess :) not anchors, but match an optional word before Guinea, then check
      my( $word, $guinea ) = /(\w+)?\s*\b(Guinea)\b/; if( $word eq ucfirst $word ){ warn "Not the Guinea I want ($word $guinea)"; }

        This will fail in some cases.

        Geographically, Guinea is thousands of miles from here. (This fails immediately because of the comma; if the comma were removed, it would still fail.)

        If what you want is to match Guinea but not New Guinea or Equatorial Guinea, then what you probably really want is a negative lookbehind assertion that specifically rules out being preceded by "New " or "Equatorial ". Similarly, a negative lookahead assertion at the end can preclude Guinea Pig and Guinnea-Bisseau.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1103274]
Approved by karlgoethebier
Front-paged by Jim
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-19 03:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found