使用 lua 从字符串中提取数字
Extracting number from string using lua
我有以下字符串作为输入:
"totalling 7,525.07"
在下面的代码中,字符串表示为 "a.message"
print (string.match(a.message, "(%d+),(%d+)(%d+)(%d+).(%d+)") )
sum = (string.match(a.message, ".-(%d+). -([%d%.%,]+)") )
上面的代码只生成数字 7 而不是整数。理想情况下,我追求的是整数,但我的代码从图中去掉了小数点。我已经尝试了各种不同的配置,但似乎没有任何进展。
您可以通过多种方式提取号码:
local a = "totalling 7,525.07" -- 7,525.07
print(string.match(a, '%S+$')) -- 7,525.07
print(string.match(a, '%d[%d.,]*')) -- 7,525.07
print(string.match(a, 'totalling%s*(%S+)')) -- 7,525.07
print(string.match(a, 'totalling%s*(%d[,.%d]*)')) -- 7,525.07
print(string.match(a, '%f[%d]%d[,.%d]*%f[%D]')) -- 7,525.07
详情
%S+$
- 匹配字符串末尾的 1+ 个非空白字符(因为数字位于字符串末尾,所以有效)
%d[%d.,]*
- 一个数字后跟 0+ 个数字,.
或 ,
个字符
totalling%s*(%S+)
- 匹配 totalling
, 0+ 个空格,然后捕获 0+ 个非空白字符和 returns 捕获的值
totalling%s*(%d[,.%d]*)
- 也是依赖于 totalling
上下文的模式,但使用第二个模式来捕获数字
%f[%d]%d[,.%d]*%f[%D]
- %f[%d]
断言非数字和数字之间的位置,%d[,.%d]*
匹配数字然后 0+ 数字,.
或 ,
和 %f[%D]
fontier 模式断言数字和非数字之间的位置。
发布这个是因为我认为人们会需要这样的东西...
function getnumbersfromtext(txt)
local str = ""
string.gsub(txt,"%d+",function(e)
str = str .. e
end)
return str;
end
-- example:
-- getnumbersfromtext("Y&S9^%75r76gu43red67tgy")
-- it will output 975764367
希望这对任何需要它的人有所帮助:)
我有以下字符串作为输入:
"totalling 7,525.07"
在下面的代码中,字符串表示为 "a.message"
print (string.match(a.message, "(%d+),(%d+)(%d+)(%d+).(%d+)") )
sum = (string.match(a.message, ".-(%d+). -([%d%.%,]+)") )
上面的代码只生成数字 7 而不是整数。理想情况下,我追求的是整数,但我的代码从图中去掉了小数点。我已经尝试了各种不同的配置,但似乎没有任何进展。
您可以通过多种方式提取号码:
local a = "totalling 7,525.07" -- 7,525.07
print(string.match(a, '%S+$')) -- 7,525.07
print(string.match(a, '%d[%d.,]*')) -- 7,525.07
print(string.match(a, 'totalling%s*(%S+)')) -- 7,525.07
print(string.match(a, 'totalling%s*(%d[,.%d]*)')) -- 7,525.07
print(string.match(a, '%f[%d]%d[,.%d]*%f[%D]')) -- 7,525.07
详情
%S+$
- 匹配字符串末尾的 1+ 个非空白字符(因为数字位于字符串末尾,所以有效)%d[%d.,]*
- 一个数字后跟 0+ 个数字,.
或,
个字符totalling%s*(%S+)
- 匹配totalling
, 0+ 个空格,然后捕获 0+ 个非空白字符和 returns 捕获的值totalling%s*(%d[,.%d]*)
- 也是依赖于totalling
上下文的模式,但使用第二个模式来捕获数字%f[%d]%d[,.%d]*%f[%D]
-%f[%d]
断言非数字和数字之间的位置,%d[,.%d]*
匹配数字然后 0+ 数字,.
或,
和%f[%D]
fontier 模式断言数字和非数字之间的位置。
发布这个是因为我认为人们会需要这样的东西...
function getnumbersfromtext(txt)
local str = ""
string.gsub(txt,"%d+",function(e)
str = str .. e
end)
return str;
end
-- example:
-- getnumbersfromtext("Y&S9^%75r76gu43red67tgy")
-- it will output 975764367
希望这对任何需要它的人有所帮助:)