Tuesday, September 18, 2007

IsNumeric Method : Regular Expression

Using int.Parse(expression) method throw an error if expression doesn't numeric; Instead of that, an alternative, is use custom method regular expression based. It returns a boolean value.

public static bool IsNumeric(string theValue){
Regex _isNumber = new
Regex(@"^\d+$");
Match m = _isNumber.Match(theValue);
return
m.Success;}

And run it.

2 comments:

Marius van Belkum said...

i would sugest to use the following regex to allow for negative values to:

Regex regNum = new Regex(@"^[-+]\d+$");

Marius van Belkum said...

this is the correct one:

positive and negative numbers and allows decimals:

Regex regNum = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");

Google