Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable contents numeric or string?

Status
Not open for further replies.

dozier

MIS
Joined
Apr 17, 2001
Messages
88
Location
US

What's the best way to test if a scalar contains a string or number?
 
use a regex to see if its a number, and if it isn't, it must be a string ??
--Paul

It's important in life to always strike a happy medium, so if you see someone with a crystal ball, and a smile on their face ...
 
A specific example of a regex to accomplish this would be shown in the following code:
Code:
$test = "12a34";
if ($test =~/^\d+$/) {
  print "This is a number!\n";
}
else {
  print "This is not a number!\n";
}
This will check the string $test to see if it is a number (1 or more numbers).
If you wanted to check if the string had zero numbers in it, you can try this.
Code:
$test = "12a34";
if ($test =~/^[^\d]+$/) {
  print "This string contains no numbers!\n";
}
else {
  print "This string contains numbers!\n";
}

Also - if you want to check specifically for words in the variable (an not just check if it has numbers or not), you can use this:

Code:
$test = "12a34";
if ($test =~/^[a-zA-Z_]+$/) {
  print "This string contains only letters!\n";
}
else {
  print "This string does not contains only letters!\n";
}

You can test each example, and change $test to contain any combination of letters or numbers...

Hope this helps!
 
Thank you both. I thought about using regexps right after I clicked submit, but decided not to respond again in order to see if anyone had any other ideas. I implemented the regexp solution and it works, but Brian's first example made me realize I left out the anchors! Oops.
 
If you need to account for decimal point and leading minus sign, /^-?\d+(\.\d+)?$/ will detect a numeric pattern. (Zero or one leading minus, one or more digits, then zero or one groups of a decimal followed by one or more digits.)

Note also that \D means "non-digit", as does the negated character class [^\d] used above.
 
Thanks for the info, mikevh, but for my uses I just needed to detect whether or not it is a positive integer.
 
Fine. The pattern I suggest will match a simple positive integer, too. If negative numbers or decimals sneak into your data at some future time, it will still work. So it's more flexible. Doesn't hurt to be prepared.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top