Regex for negative and positive numbers

11,947

This the regex to get positive and negative numbers :

^-?\d+$

If you want decimal numbers you can use this :

^-?\d+(\.\d{1,2})?$

The parameter {1,2} at the end is for precision of your decimal number.

Share:
11,947
midda25
Author by

midda25

Updated on June 07, 2022

Comments

  • midda25
    midda25 almost 2 years

    I need a regex for an input field to allow negative and positive numbers and no alphabet/special characters. I have seen other people achieve this but they allow the minus sign at any point in the string whereas I only want to allow the minus sign at the beginning of the string.

    Note: I want to allow the user to use the arrow, del, home keys etc.

  • georg
    georg over 7 years
    [-]{0,1} can be written shorter as -?
  • midda25
    midda25 over 7 years
    This isnt quite what i wanted. I actually need to stop user input in a text field if it is not a number, however, I want to allow the minus sign as a first character and nowhere else in the string
  • midda25
    midda25 over 7 years
    I think ill just use the HTML5 number input
  • Mattasse
    Mattasse over 7 years
    Use number input is the best way for your problem. But if you really want use regex you can use one of two regex above.