Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Regex {3} matches 3 or more?

by pritesh_ugrankar (Monk)
on Sep 05, 2020 at 13:06 UTC ( [id://11121372]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-03-29 00:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found