When I’m developing the online form creator that enables the users to create form fields that accept only certain type of numbers, I need to verify if a given string is a valid natural number such as 1, 2, 3, 4, …. I’m writing the code / functions in PHP but you can literally use the regular expression in other programming languages as well. I use the following function to distinguish strings if they are natural numbers or positive integers.
function isNaturalNumber($subject) {
return preg_match('|^[1-9][0-9]*$|', $subject);
}
You can add for a leading plus sign as well:
^+?[1-9][0-9]*$
Regular Expression for Negative Integers?
Negative integers are –1, –2, –3, …. Just add a minus sign before the regular expression for positive integers:
^-[1-9][0-9]*$
Regular Expression for Non-negative Integers?
That is, 0, 1, 2, 3, 4, …. By a little help of the isNaturalNumber function, you can use this function to check if a string is a legal non-negative integer:
function isNonNegativeInteger($subject) {
// @^(0|[1-9][0-9]*)$@
if ($subject == '0' || isNaturalNumber($subject)) {
return true;
}
}
Or if you insist on using a regular expression:
function isNonNegativeInteger($subject) {
return preg_match('@^(0|[1-9][0-9]*)$@', $subject);
}
PHP functions to check if a string is a valid integer?
Just use the above functions in combination or the native is_integer() function of PHP.
function isInteger() {
return isNegativeInteger($subject) || isNonNegativeInteger($subject);
}