Regex Matching numbers with floating point

前端 未结 5 2069
感情败类
感情败类 2020-12-17 16:55

I have this pattern:

[0-9]*\\.?[0-9]

It matches numbers but it also matches 3.5.4 as:

  1. 3.5
  2. .4

How to f

相关标签:
5条回答
  • 2020-12-17 17:39

    To match a json number:

    ^[-]?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$
    

    JSON number

    Use this regex to match .123:

    ^[-]?((0|[1-9][0-9]*)(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?$
    
    0 讨论(0)
  • 2020-12-17 17:41

    Your regex is not anchored. If you want to match lines that contain only numbers and nothing else use:

    ^[0-9]*\.?[0-9]$
    
    0 讨论(0)
  • 2020-12-17 17:49

    You have to decide if you want to accept numbers without leading zeros (eg .123). If you don't then the regex is easy:

    ^-?[0-9]+(\.[0-9]+)?$
    

    If you do then it's a little more complex:

    ^-?(?:[0-9]+|[0-9]*\.[0-9]+)$
    

    Both presume that a decimal point must be followed by at least one digit. If you don't accept negative numbers then the leading -? is unnecessary.

    0 讨论(0)
  • 2020-12-17 17:49

    You should not use a regex for this unless you really need to.

    Instead, you should use your language's built-in number parsing methods.

    I assume from your other questions that you're using Javascript; if so, you should call parseFloat.

    0 讨论(0)
  • 2020-12-17 17:53

    Updated answer after comment from poster:

    Use lookahead / lookbehind to make sure that the characters before and after are spaces:

    Here's a version that closely matches yours, but that won't make partial matches:

    (?:^|(?<=\s))[0-9]*\.?[0-9](?=\s|$)
    

    For both these examples, when run on the string 1 2.3.4 5.6 it matches only 1 and 5.6.

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