How to Code RegEx for Positive Number w/Optional Decimal places and Whitespace
Updated August 31, 2010
Here's a tip on how to create a Regular Expression to validate a positive number that can optionally have a decimal with decimal places. The Regular Expression will also be valid if there are any whitespace before or after the number. I'm using this Regex to evaluate a positive number entered into a TextBox, that's why I'm checking for Whitespace. In my code behind, I am trimming the whitespace from the number entered from the textbox.
Here is the regular expression that validates a positive number (with optional decimal places and whitespace):
^( *[0-9]*| *)((\.)?[0-9]+ *| *)$
If you use ASP.NET, here is the Validation expression within a RegularExpressionValidator control:
ValidationExpression="^( *[0-9]*| *)((\.)?[0-9]+ *| *)$"
NOTE: This expression will NOT validate true when a number has a decimal point without decimal places. For instance, '3.' will NOT work, instead you must enter '3.0'. However, the number '.3' will be valid.