如何匹配带小数点的数字

3
我希望能够在字符串中设置两个不同数字到各自独立的变量。
我曾使用字符串 "100,125" 并成功获取了两个数字,但一旦将字符串更改为包含小数点(例如 "100.172,125.181"),它只返回小数点后的数字。
local x, y = string.match("100,125", "(%d+),(%d+)")
--this code works, making x = 100 and y = 125

然而。
local x, y = string.match("100.134,125.122", "(%d+),(%d+)")
--this did not work correctly

使用后一种方法后,我得到的变量x和y是小数点后面的数字。我认为我应该重新格式化字符串,变成类似于“100.1x125.5”的形式,但我不确定。感谢您,对初学者问题表示歉意。

2个回答

2

%d 只匹配0到9之间的数字。你也想匹配小数点,所以应该使用集合 [%d.] 来匹配任何数字或者一个句号。

因此,将模式更改为以下内容:

local x, y = string.match("100.134,125.122", "([%d.]+),([%d.]+)")
print(x)
print(y)

这将正确地打印:

最初的回答
100.134
125.122

0

你可能想要安装split rock

> split = require("split")
> s = "100.134,125.122"
> x,y = table.unpack(split.split(s, ","))
> x
100.134
> y
125.122

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接