gpt4 book ai didi

lua - 使用lua从字符串中提取数字

转载 作者:行者123 更新时间:2023-12-01 22:14:38 24 4
gpt4 key购买 nike

我有以下字符串作为输入:

“总计 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

参见 Lua demo

详情

  • %S+$ - 匹配字符串末尾的 1+ 个非空白字符(因为数字在字符串末尾,所以有效)
  • %d[%d.,]* - 一个数字后跟 0+ 个数字,., 字符
  • totalling%s*(%S+) - 匹配totalling,0+个空格,然后捕获0+个非空白字符并返回捕获的值
  • totalling%s*(%d[,.%d]*) - 也是一种依赖于 totalling 上下文的模式,但使用第二种模式来捕获数
  • %f[%d]%d[,.%d]*%f[%D] - %f[%d] 断言 a 之间的位置非数字和数字,%d[,.%d]* 匹配一个数字,然后匹配 0+ 个数字,.,%f[%D] fontier 模式断言数字和非数字之间的位置。

关于lua - 使用lua从字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46794989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com