开发者

Need a Regex to Parse This Line 58.21 -13.73 57 -1

Need help parsing the numbers from this line in Lua.

58.21 -13.73 57 -1

I currently am at this: [1-9][0-9] which I know is not correc开发者_JS百科t as it does not return the minus and does not handle the decimal.

Thanks,

Dave


s="58.21 -13.73 57 -1"
for w in s:gmatch("%S+") do print(w) end

This pattern extracts all words from a line, a word being a run of non-whitespace characters.


This is not a job for regex. Here is the simple implementation in python:

>>> s = '58.21 -13.73 57 -1'
>>> [float(i) for i in s.split()]
[58.21, -13.73, 57.0, -1.0]

The principle however is universal: split on space and convert to numeric type if necessary.


In Lua:

(%-?%d+%.?%d+)%s+(%-?%d+%.?%d+)%s+(%-?%d+%.?%d+)%s+(%-?%d+%.?%d+)

Example:

local a, b, c, d = ("58.21 -13.73 57 -1"):match(
    "(%-?%d+%.?%d*)%s+(%-?%d+%.?%d*)%s+(%-?%d+%.?%d*)%s+(%-?%d+%.?%d*)"
  )
print(a, b, c, d) --> 58.21 -13.73  57  -1

You may (or may not) want to convert returned values to numbers.


I'm assuming by "parse" you mean, you want a Regular Expression that will match a number. In the string you provided, you would want the matches to be:

  • 58.21
  • -13.73
  • 57
  • -1

The pattern I would probably use is ([^ ]+). It will find anything except for space, which, in your string, would be numbers with (potentially) decimal points and signs.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜