Home: Perl Programming Help: Intermediate:
regex integer



gaetan3009
New User

Nov 2, 2017, 8:11 AM


Views: 2026
regex integer

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.


ogit2
Novice

Nov 2, 2017, 8:53 AM


Views: 2024
Re: [gaetan3009] regex integer

Hi

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.


Code
 
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.";
}
else
{
$return = $return . " and is not an integer.";
}
}
else
{
$return = $return . $var . " is not a number";
}

return $return;

}



BillKSmith
Veteran

Nov 2, 2017, 12:33 PM


Views: 2015
Re: [gaetan3009] regex integer

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.

Change:

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

Good Luck,
Bill


Laurent_R
Veteran / Moderator

Nov 3, 2017, 12:07 AM


Views: 2007
Re: [gaetan3009] regex integer

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:

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