Regular Expression limiting match only for "." difficulties
I am developing a app for WP7 and using this for my RegEx
new System.Text.RegularExpressions.Regex(@"\D\.{1}");
Basically I want开发者_StackOverflow社区 user to input only numeric data with one .
allowed for double
, it works when user inputs only 1 period but app crashes as soon as another period is added
I would personally not use Regular Expressions for this.
bool isInputGood(string input) {
double d;
return double.TryParse(input, out d);
}
Of course, this won't reject something like 123.456.789
, but it WILL accept something like 123.456 e+5
new System.Text.RegularExpressions.Regex(@"^\s*[0-9]+(\.[0-9]+)?\s*$");
This checks the whole string (anchored with ^
and $
) and matches "legitimate" numbers.
Note that this is not a suitable check to be used in applications which may run on different regional settings, as the decimal separator may vary. Why not check the input by doing a double.TryParse()
instead?
精彩评论