Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

specific numbers of digits

by emichswimr (Initiate)
on Mar 19, 2003 at 04:27 UTC ( [id://244237]=perlquestion: print w/replies, xml ) Need Help??

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

I want to specify a certain number of digits to match. ex. a zip code has 5 digits, 48197 $zip =~ /\d{5}/ while this will make sure that there is 5 digits it will also accept 6 digits. Suggestions?

Replies are listed 'Best First'.
Re: specific numbers of digits
by pg (Canon) on Mar 19, 2003 at 05:07 UTC
Re: specific numbers of digits
by Limbic~Region (Chancellor) on Mar 19, 2003 at 19:05 UTC
    emichswimr,
    If you know that your input string will only be a sequence of digits, then use pg's solution of anchoring with ^ and $. If you need to match within a string, then one of these may help.

    /\b\d{5}\b/; or /\D\d{5}\D/; or /\s+\d{5}\s+/;
  • The first one breaks on word boundaries (any character not in \w)
  • The second one breaks on any non digit
  • The third one breaks on white spaces

    Cheers - L~R

    Update: Changed introduction to explain why these solutions may be more flexible then the ones that anchor with ^ and $

Re: specific numbers of digits
by lacertus (Monk) on Mar 19, 2003 at 04:33 UTC
    Put an upper limit on that match, say you want between 5 and 7 digits:
    my $ID = 0123456; if ($ID =~ /\d{5,7}/ { do this... }
    So for your case, perhaps /\d{5,5}/
      This does not meet his requirement, as your regexp still matches 6-digit strings i.e. your regexp still matches strings like "123456".

Re: specific numbers of digits
by pfaut (Priest) on Mar 19, 2003 at 12:28 UTC

    Add a negative lookahead assertion to make sure the next character is not a digit: /\d{5}(?!\d)/

    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';

      That will still match 6 digits, it'll just match the last 5 rather than the first 5. To match only 5 digits you need an assertion at both ends:

      m{ (?>! \d) # not after a digit \d(5} (?! \d) # not before a digit }x;

      Hugo
Re: specific numbers of digits
by MZSanford (Curate) on Mar 19, 2003 at 14:11 UTC

      Sorry to point this out, but..

      $x = "123456"; if ( $x =~ /\d{5,5}/ ) { print "wrong"; }

      Still matches 123456

      This will do the trick

      $x = "123456"; if ( $x =~ /^\d{5}$/ ) { print "right"; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-03-28 13:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found