I Need a regex to validate 0-9
and allow .
and -
characters.
Following is working for 0-9
and .
characters:
Regex invalidCharsRegex = new Regex(@"^*[0-9\.]+$");
I Need a regex to validate 0-9
and allow .
and -
characters.
Following is working for 0-9
and .
characters:
Regex invalidCharsRegex = new Regex(@"^*[0-9\.]+$");
Your regex is weird...
Regex invalidCharsRegex = new Regex(@"^*[0-9\.]+$");
Remove the first asterisk, it's not doing anything good.
And to allow -
characters, you simply add it to the character class. Also, you don't need to escape the dot in a character class:
Regex invalidCharsRegex = new Regex(@"^[0-9.-]+$");
If you're trying to validate a number, this regex will have to be revised, because the regex will accept ----
or .....
. Something a bit like this for integer/floating numbers:
Regex invalidCharsRegex = new Regex(@"^\-?[0-9]+(?:\.[0-9]+)?$");
Regex invalidCharsRegex = new Regex(@"(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )");
This will allow numbers like 1, 1.2, .1 etc