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

后端 未结 2 991
小蘑菇
小蘑菇 2020-12-06 10:58

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

Please help.

相关标签:
2条回答
  • 2020-12-06 11:12

    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

    0 讨论(0)
  • 2020-12-06 11:27

    ^[-+]?[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 [.,]

    0 讨论(0)
提交回复
热议问题