in reply to "Complete match" regexes

Use  ^ and $ in your regex (for the beginning and the end of the line) :

while (<>) { if ( /^\w{5}\s\w{4}$/ ) { print "This is a 5-letter word followed by a four-letter word\n"; } }

BTW: more details in perldoc perlre (it's a must read ;-)

Replies are listed 'Best First'.
Re: Re: "Complete match" regexes
by japhy (Canon) on Feb 02, 2001 at 20:42 UTC
    You might want to use the \z anchor instead of the $ anchor -- \z is explicit end-of-string, but $ can match right before a newline at the end of a string.

    japhy -- Perl and Regex Hacker
Re: Re: "Complete match" regexes
by $code or die (Deacon) on Feb 02, 2001 at 20:47 UTC
    If you aren't fussed about leading and trailing spaces, you can modify the regex thusly:
    /^\s*\w{5}\s\w{4}\s*$/
    </code> Update: Yeah, I know the question was pretty explicit that he wanted to match exactly a 5 letter word followed by a 4 letter word. The question had already been answered so I posted this in case it's of use to anyone else.

    It happens occasionally that you think - I want a regex to allow x and and make it too unforgiving to allow for mistakes in user input. Correct me if I'm wrong, but I don't think the code I posted is incorrect?

    Update 2: Fastolfe pointed out that I used character classes when I didn't need them so I took them out. He was quite right - not sure why I used them, but I don't think they did any harm, I originally posted: /^[\s]*\w{5}\s\w{4}[\s]*$/

    $code or die
    Using perl at
    The Spiders Web