3

Hello I am using the following regex command to only allow numbers be inputted into a text field

Regex rgx = new Regex("[^0-9]"); 

however this obviously doesnt allow the inputting of positive and negative signs +/-. I would like to be able to input -9 for a negative value but when i do it comes back as 09 instead. Any help in getting the regular expression right would be appreciated.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
Alan Fletcher
  • 283
  • 1
  • 13
  • 24

3 Answers3

4

There you go, this one works 100% just tested to make sure ;)

Regex r = new Regex("^([-+]?)?[0-9]+(,[0-9]+)?$");
Thalmann
  • 101
  • 3
  • Regex rgx = new Regex("[^-][^0-9]+"); it does work but weirdly for exactly what im trying to do, the code i entered here works best for me. thnk you for all your help and time. its appreciated – Alan Fletcher Mar 23 '13 at 00:49
  • 1
    The one you have written should NOT work as a regular expression in C# with the input '[^-]' it allows every character but the minus... – Thalmann Mar 23 '13 at 00:53
0

Your expression resolves to everything except 0 to 9 in my view... To allow any number with positive or negative sign I would use the following expression:

([-+]{0,1}[0-9]+)

+ or - at the beginning 0 or 1 times, and any quantity>0 of 0...9 after.

Appleshell
  • 7,088
  • 6
  • 47
  • 96
0

Regex rgx = new Regex("[^-][^0-9]+");

Alan Fletcher
  • 283
  • 1
  • 13
  • 24