Aung Kaung Hein
Aung Kaung Hein

Reputation: 1566

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

Negative Values

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.

Upvotes: 11

Views: 25279

Answers (1)

brandonscript
brandonscript

Reputation: 72855

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

Upvotes: 14

Related Questions