It is easy to validate numbers using REGEXP. You can validate any negative/positive (or both) Integer/Decimal number easily. Before doing anything, just trim your string(to know how to trim, check here http://icfun.blogspot.com/2008/02/perl-trim-string.html), and then validate your number with regexp. I'm giving few example of regular expression.
1) To validate an Integer number (can be positive or negative) your regular expression will be
2) To validate a decimal number (can be positive or negative) your regular expression will be as below. This will work for Integer number handling too.
The above regular expression will work with Perl/PHP/Python/Ruby. I didn't tested with java/.NET and other languages.
For PHP use preg_match() function.
For Python use the function findall from regular expression class. that means re.findall()
For Ruby and Perl, use it like, variable_name =~ /REGEXP HERE/
1) To validate an Integer number (can be positive or negative) your regular expression will be
^-{0,1}\d+$
2) To validate a decimal number (can be positive or negative) your regular expression will be as below. This will work for Integer number handling too.
^-{0,1}\d*\.{0,1}\d+$
The above regular expression will work with Perl/PHP/Python/Ruby. I didn't tested with java/.NET and other languages.
For PHP use preg_match() function.
For Python use the function findall from regular expression class. that means re.findall()
For Ruby and Perl, use it like, variable_name =~ /REGEXP HERE/
Comments
No, the '^-' also fails.
Cheers,
Paul.
Pattern p = Pattern.compile("(^-{0,1}\\d*\\.{0,1}\\d+$)");
Matcher m = p.matcher(str);
if (m.find() == true){
System.out.println("Number is valid");
}
^-{0,1}\d+$
is more clearer then
^-?\d+$