CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Intermediate:
regex integer


New User

Nov 2, 2017, 8:11 AM

Post #1 of 4 (7542 views)
regex integer Can't Post

Hi everybody,
I am trying to use regex. I would like to check if a input is a integer.
For this i have :
my $num = <STDIN>;
chomp $num;
if ($num =~ /^\d$/) {
print "ok\n";
It seems ok. Whats the problem pls?
Thank you. Have a good day.


Nov 2, 2017, 8:53 AM

Post #2 of 4 (7540 views)
Re: [gaetan3009] regex integer [In reply to] Can't Post


This may not answer your question, but may help. I am a beginner. I am sure someone will compact the code and come up with something even better but the below seems to work nicely with strings and checks for numbers and integers.

print numb("0") . "\n";
print numb("1") . "\n";
print numb("1.2") . "\n";
print numb("A") . "\n";
print numb("1.25B") . "\n";
print numb("-18") . "\n";
print numb("-18.124") . "\n";
print numb("-0.124") . "\n";

sub numb

my $var = shift;
my $return = "";
if ( $var =~ /^[0-9,.E]+$/ || $var =~ /^[+-][0-9,.E]+$/ )
$return = $return . $var . " is a number";

if ($var =~ /^[+-]?\d+$/ )
$return = $return . " and is an integer.";
$return = $return . " and is not an integer.";
$return = $return . $var . " is not a number";

return $return;



Nov 2, 2017, 12:33 PM

Post #3 of 4 (7531 views)
Re: [gaetan3009] regex integer [In reply to] Can't Post

Your script works fine for decimal integers 0 through 9 with no leading or trailing whitespace. Before you can extend it, you must decide what you mean by integer. Do you want to include a sign and/or leading zeros? Do you mean decimal integers only, or do you want to include binary, octal, hex, or even roman numerals? Do you mean normal strings or perl constants? (not an issue for decimal only). Is there a maximum number of digits? Ignore commas?

The solution is simple if you wish to accept only unsigned decimal integers (including zero) of any length, preceded by any number of leading zeros, with no whitespace or commas.


#if ($num =~ /^\d$/) {  
if ($num =~ /^\d+$/) {

Good Luck,

Veteran / Moderator

Nov 3, 2017, 12:07 AM

Post #4 of 4 (7523 views)
Re: [gaetan3009] regex integer [In reply to] Can't Post

Hi gaetan3009,

your regex will match only single digits. If you want to match larger integers, add a + quantifier after the \d, meaning one or more digits:

if ($num =~ /^\d+$/) {


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives