Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re: Re: compare stdin for a number

by Vautrin (Hermit)
on Mar 12, 2004 at 21:00 UTC ( #336265=note: print w/replies, xml ) Need Help??

in reply to Re: compare stdin for a number
in thread compare stdin for a number

I know that the first time I was learning about regular expressions, "do ___" was much less helpful to me if it didn't include an explanation of why it should be done. I am including one here for completeness.

The following code

print "good input\n" if /^\d{5}$/;

Should Could be rewritten:

print "good input\n" if /^\d{5,5}$/;

This is because {}s can contain 2 numbers seperated by a comma. The number on the left is the minimum number of the charachters (or things). The number on the right is the maximum number of charachters (or things). The charachter or thing is whatever is to the left of the {}s. So, \d{5,5} says 5 digits and only 5 digits, whereas \d{5} says at least 5 digits -- but possibly more. (Note that \d means a charachter that represents a number -- i.e. a digit)

Of course, the reason the original regular expression will still work is the ^ and $ charachter mean "beginning of a line" and "end of a line", respectively. So my regular expression says "at least 5 digits but not more then 5 digits which start on the beginning of a line and end at the end of a line" while the original regular expression says "At least 5 digits between the beginning and end of a line -- and possibly more".

Of course, the thing we have to pay attention to here is that mine would fail if we tried to match the string "Foo\n12345\nBar" This is because it fits all the constraints of the regular expression. However, because of the angle brackets <> -- which reads in a single line at a time, you know you can only have one line.

Update: Thanks for pointing out my mistake Tom

Want to support the EFF and FSF by buying cool stuff? Click here.

Replies are listed 'Best First'.
Re: Re: Re: compare stdin for a number
by tcf22 (Priest) on Mar 12, 2004 at 21:33 UTC
    /\d{5}/ means exactly 5(same as /\d{5,5}/).
    /\d{5,}/ means 5 or more.

    - Tom

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://336265]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2022-05-28 21:14 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (101 votes). Check out past polls.