Wednesday, March 26, 2008

Regular Expression to handle negative number

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

^-{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/

6 comments:

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.

Cheers,
Paul.

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
^-{0,1}\d+$
is more clearer then
^-?\d+$

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...