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

Hi Monks,

Not sure what I am doing wrong, so thought of posting this here.

use strict; use warnings; use diagnostics; while (<STDIN>) { chomp; if (/[0-9]{3}/) { print "\tIt Matches.\n"; } else { print"\tIt doesn't match.\n"; } }

Here's what it does:

D:\perlscripts>perl test.pl 1 It doesn't match. 12 It doesn't match. 123 It Matches. 12345 It Matches. 1234567890 It Matches. D:\perlscripts>

I thought {3} should match only 3, not more or less. Please correct if my understanding is wrong.

</code>

Replies are listed 'Best First'.
Re: Regex {3} matches 3 or more? (Anchors)
by LanX (Saint) on Sep 05, 2020 at 13:36 UTC
    > I thought {3} should match only 3, not more or less.

    Yes, but in your case anywhere.

    If you want to only match strings with exactly three digits you need anchors for start and end of string.

    /^[0-9]{3}$/

    See perlreref#ANCHORS

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

      Hi Rolf,

      Thank you for the clarity.