开发者

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

what the regular expression of a line of string containing ONLY float numbers separated with spaces or tabs. The float number can be negative, 开发者_如何学JAVAlike -999.999


(?:-?(?:\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


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+)+$/


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜