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

#!/usr/bin/perl use strict; use warnings; my @names; @names = ("by MRCUS ELN AP","AP, Ctina Appe","John Ap Smith","Applicat +ion Specialist"); foreach my $name (@names){ $name =~ m/AP/i; print "$name\n"; }
How to match only "by MRCUS ELN AP","AP, Ctina Appe","John Ap Smith" and not "Application Specialist"
only if two letters exists as "AP" i should match the names
Please tell me how to do it.

Replies are listed 'Best First'.
Re: match the name
by Your Mother (Archbishop) on Nov 04, 2009 at 05:21 UTC

    Sounds like homework. :( Reading perlre will do the trick. A good hint here is that all the other "ap"s have something that "application" doesn't: a boundary instead of another letter. You'll also need to next unless or something so you only print if there was a match. Right now the match is irrelevant to the code flow because you're not doing anything with it.

Re: match the name
by davido (Cardinal) on Nov 04, 2009 at 05:21 UTC

    m/AP(?:\W|$)/i;

    Approximately translated: match case insensitively AP, followed by either a non-word character, or the end of the string.

    This makes the assumption that AP should match unless it's immediately followed by an alpha character.

    You could also just force a word boundary and have a similar outcome:

    m/AP\b/i

    Updated: Added a colon in the appropriate place.

    Second update: It's been mentioned to me that it is possible that the OP wants a word boundary before AP. Though it wasn't explicit in his writeup, you could use either of the two RE's to make that happen:

    m/\bAP(?:\W|$)/i; #or easier... m/\bAP\b/i;

    Dave

Re: match the name
by ikegami (Patriarch) on Nov 04, 2009 at 06:15 UTC
    You were rather unclear. Perhaps you want
    /(?<![a-z])AP(?![a-z])/i
    Or maybe
    /(?<!\S)AP(?!\S)/i
Re: match the name
by happy.barney (Friar) on Nov 04, 2009 at 13:42 UTC
    I think that you are looking for \b - word boundary.
    m/ \b ap \b /xi;