lua:如何从字符串中捕获整数或点数?

问题描述 投票:0回答:1

我有

S = 564186207, 399.4989929, ABC, 度, 2425, 335.232

这个字符串

我想捕获唯一的整数和点数

这样

your text
string.gfind(S, ???) --> 564186207, 399.4989929, 2425, 335.232

我试过了

your text
string.gfind(S, "%d+")

your text
string.gfind(S, "%d*")

your text
string.gfinc(S, "^%d")

如何捕获该字符串中的唯一数字?

请帮助我

string design-patterns lua match
1个回答
0
投票

较新版本的 Lua 已将

gfind
替换为
gmatch
,请替换代码中的函数以匹配您的版本。

由于您想要匹配整数和小数,因此您将需要一个包含两者的模式。您想要匹配:一系列数字,可能后跟一个点,然后是更多数字。

local S = "564186207, 399.4989929 , ABC, degds, 2425, 335.232"
local pattern = "(%d+%.?%d*)" --Any number of digits, followed by an optional 'dot' and then more zero or digits (this could match against "123." but given your example input it hopefully won't be an issue
local matches = string.gmatch(S,pattern)
for found in matches do
    print("Matched:",found)
end

输出:

Matched:    564186207
Matched:    399.4989929
Matched:    2425
Matched:    335.232
© www.soinside.com 2019 - 2024. All rights reserved.