Regular expressions match floating point number but not integer

后端 未结 2 2050
温柔的废话
温柔的废话 2020-12-06 19:28

I have a problem to define a regexp that matches floating point numbers but do NOT identify integers.

I have the following regular expression, which matches floating

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

    This one should suit your needs:

    [+-]?([0-9]+\.([0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?
    
    0 讨论(0)
  • 2020-12-06 20:26

    If your regex flavor supports lookaheads, require one of the floating-point characters before the end of the number:

    ((\+|-)?(?=\d*[.eE])([0-9]+\.?[0-9]*|\.[0-9]+)([eE](\+|-)?[0-9]+)?
    

    Additional reading.

    Here is also a slightly optimized version:

    [+-]?(?=\d*[.eE])(?=\.?\d)\d*\.?\d*(?:[eE][+-]?\d+)?
    

    We start with an optional + or -. Then we require one of the characters ., e or E after an arbitrary amount of digits. Then we also require at least one digit, either before or after the string. The we just match digits, an optional . and more digits. Then (completely optional) an e or an E and optional + or - and then one or more digits.

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