regular expression: a line of string contains only float numbers and tab/spaces

前端 未结 3 1244
悲&欢浪女
悲&欢浪女 2020-12-21 14:07

what the regular expression of a line of string containing ONLY float numbers separated with spaces or tabs. The float number can be negative, like -999.999

相关标签:
3条回答
  • 2020-12-21 14:46

    Let's come up with a regex for a float, and then see what we can do about the rest.

    A float is:

    • An optional negative sign
    • Followed by a number of digits
    • Followed by an optional decimal point and then more digits
    • Followed be "e"
    • Followed by a number of digits (with an optional sign).

    Put that together, and we get:

    /-?[0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)?/
    

    Now, this is pretty loose, but you can tweak it if you want to tighten it up a little. Now, for any number of these with spaces in between, it's pretty trivial:

    /^(F\s+)+$/
    

    Put it all together, we end up with:

    /^(-?[0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)?\s+)+$/
    
    0 讨论(0)
  • 2020-12-21 14:53
    (?:-?(?:\d+(?:\.\d*)|.\d+)[ \t]*)+
    

    is one possibility. In more readable format:

    (?:
      -?                 # Optional negative sign
      (?:
        \d+(?:\.\d*)     # Either an integer part with optional decimal part
        |
        .\d+             # Or a decimal part that starts with a period
      )
      [ \t]*             # Followed by any number of tabs or spaces
    )+                   # One or more times
    
    0 讨论(0)
  • 2020-12-21 14:57

    A regex for a float would look like this: -?\d+\.?\d+

    A whitespace separator looks like this: \s

    Put them together, allow it to repeat, make sure the end has a float (not a separator):

    ((-?\d+\.?\d*)\s)*(-?\d+\.?\d*))
    

    The escaping and \d vs [0-9] might change, depending on your flavor of regex.

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