Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex which allow minus (-) sign only

I am using this regex to validate input strings as decimal values in Textbox.

^\d{1,16}((\.\d{1,4})|(\.))?$

Now I want to allow negative decimal values. I have found many similar questions on SO. And I tried something like these:

/^-?, (\+|-)?, \.\d{1,4}\- but not working.

The reason I asked a new question here because I am using Textbox TextChanged event and I need to check each character entered into the Textbox.

So the first character, minus(-) sign, should be valid

Valid Values:

Positive Values

  • 1
  • 1.
  • 1.1
  • 1.1111

Negative Values

  • -
  • -1
  • -1.
  • -1.1
  • -1.1111

The Regex that I have above validate for positive values. How can I modify my Regex to allow negative values? Any help will be very much appreciated.

like image 658
Aung Kaung Hein Avatar asked Nov 27 '13 07:11

Aung Kaung Hein


1 Answers

You need to escape the minus sign because - is a special character.

Try (\+|\-)? (note the backslash).

Edit: Not sure if this will do what you want, but it's a lot simpler:

^\-?\d*\.?\d*$

Will match any decimal (1 to infinite chars on either side of a decimal, with or without a -). More details here: http://regex101.com/r/rP7cG2

like image 156
brandonscript Avatar answered Sep 22 '22 21:09

brandonscript