在编程的过程中,很多时候都需要从字符串中提取数字,在lua语言中提取数字的方法,有两种
1.直接提取
通过循环的方式,对字符串中的字符挨个判断,查找一组数字,包含“-”和“.”,变为数字即可
function GetNumber(str)
local num = ""
local flg = 0
while (str) > 0 do
local c = (str, 1, 1)
if c >= "0" and c <="9" then
num = num .. c
flg = 1
elseif c == "-" and flg == 0 then
num = c
elseif c == "." then
num = num .. c
elseif flg > 0 then
break
else
num = ""
end
if (str) > 1 then
str = (str, 2)
else
str =""
end
end
return num, str
end
str = "-35(±3.1×2.5)%/-10.5"
while (str) > 0 do
n, str = GetNumber(str)
print(n, str)
end
2.使用库函数提取
通过Lua的字符串函数gmath提取数字,这里要用到一些正则表达式的知识和技巧
Lua中方法详解如下:
字符类:(character classes)
. all characters
%a letters
%c control characters
%d digits
%l lower -case letters
%p punctuation characters
%s space characters
%u upper-case letters
%w alphanumeric characters
%x hexadecimal digits
%z the character whose representation is 0
单个字符(除^$()%.[]*+-?外): 与该字符自身配对
.(点): 与任何字符配对
%a: 与任何字母配对
%c: 与任何控制符配对(例如\n)
%d: 与任何数字配对
%l: 与任何小写字母配对
%p: 与任何标点(punctuation)配对
%s: 与空白字符配对
%u: 与任何大写字母配对
%w: 与任何字母/数字配对
%x: 与任何十六进制数配对
%z: 与任何代表0的字符配对
%x(此处x是非字母非数字字符): 与字符x配对. 主要用来处理表达式中有功能的字符(^$()%.[]*+-?)的配对问题, 例如%%与%配对
[数个字符类]: 与任何[]中包含的字符类配对. 例如[%w_]与任何字母/数字, 或下划线符号(_)配对
当上述的字符类用大写书写时, 表示与非此字符类的任何字符配对. 例如, %S表示与任何非空白字符配对.例如,’%A’非字母的字符
‘%’ 用作特殊字符的转义字符,因此 ‘%.’ 匹配点;’%%’ 匹配字符 ‘%’。转义字符 ‘%’不仅可以用来转义特殊字符,还可以用于所有的非字母的字符。当对一个字符有疑问的时候,为安全起见请使用转义字符转义他。
+ 匹配前一字符1次或多次
* 匹配前一字符0次或多次
- 匹配前一字符0次或多次
? 匹配前一字符0次或1次
从字符串中提取数字的代码如下:
function GetNumber(str)
for s in (str, "%-?%d+%.?%d?") do
local i, j = (str, s)
if j>0 and j+1 < (str) then
str = (str, j+1)
else
str =""
end
return s*1, str
end
return 0, ""
end
str = "-35(±3.1×2.5)%/-10.5"
while (str) > 0 do
n, str = GetNumber(str)
print(n, str)
end
运行结果为:
-35 (±3.1×2.5)%/-10.5
3.1 ×2.5)%/-10.5
2.5 )%/-10.5
-10.5
相对来说,代码看起来简洁,效率要高一些。