1

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\.]+$");
Ibrahim Najjar
  • 19,178
  • 4
  • 69
  • 95
user2759571
  • 63
  • 1
  • 1
  • 3

2 Answers2

7

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]+)?$");
Jerry
  • 70,495
  • 13
  • 100
  • 144
0
Regex invalidCharsRegex = new Regex(@"(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )");

This will allow numbers like 1, 1.2, .1 etc

Irfan TahirKheli
  • 3,652
  • 1
  • 22
  • 36