Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that accepts floating point numbers and minus (-) sign

Tags:

regex

I want a regular expression that will accept only floating point numbers from 0 to 9 and minus sign.

Please help.

like image 509
fibnochi Avatar asked Dec 03 '12 15:12

fibnochi


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

Does decimal allow negative number?

If UNSIGNED is used with DECIMAL , negative values are not allowed.

How do you specify in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


2 Answers

^[-+]?[0-9]*\.?[0-9]+$

  • ^ - start of string
  • [-+]? - 0 or 1 sign indicator
  • [0-9]* - 0 or more integers
  • \. - the character . (. is used in regex to mean "any character")
  • [0-9]+ - 1 or more integers
  • $ - the end of the string

If you are instead using the comma as a decimal seperator, use , instead of \.

If you are using both/either, you can use [.,]

like image 85
James Webster Avatar answered Oct 23 '22 07:10

James Webster


Try ^[-+]?[0-9]*[.,]?[0-9]+$.

This regular expression will match an optional sign, that is either followed by zero or more digits followed by a dot and one or more digits (a floating point number with optional integer part), or followed by one or more digits (an integer).

Source: http://www.regular-expressions.info/floatingpoint.html - altered to work with commas as decimal separator

like image 32
D_4_ni Avatar answered Oct 23 '22 07:10

D_4_ni