Wednesday, March 26, 2008

Regular Expression to handle negative number

Share at Facebook

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, 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/


Anonymous said...

Instead of {0, 1} you can use "?". And the "$" on the end allows a newline character. Also, using regular expressions for validating a number, even if it's negative or has decimals, is not too smart

Anonymous said...

Ok, but how than is a smart way works???

Anonymous said...

Unfortunately this does not work for Java. I had something similar to what you have proposed however note the grouping (-?) does not group the '-' when it occurs. My approach was to use the pattern p="\\b(-?)(\\d)+(.?)(\\d?)+\\b".
No, the '^-' also fails.


Wolf said...

String str = "-1990.212";
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");

Anonymous said...

well for PERL (-?\d+\.?\d+) would me much better then the shown above.

Николай Мишин said...

I think
is more clearer then