在Lua中有没有一种高效而优雅的方法来截断这样的数字? 我想做什么
我想做的很简单。我想使用Lua检查Plist文件中的行 假设Plist中的一行是在Lua中有没有一种高效而优雅的方法来截断这样的数字? 我想做什么,lua,lua-patterns,Lua,Lua Patterns,我想做的很简单。我想使用Lua检查Plist文件中的行 假设Plist中的一行是-1.00,我需要将.00切掉,使其成为-1 我所做的 我使用一个函数读取整个文件内容,并逐行检查和替换 local function doLineClean( cont ) newcont = '' string.gsub( cont, "(.-)\r?\n", function(line) if string.match( line, "<integer>.-<%
-1.00
,我需要将.00
切掉,使其成为-1
我所做的
我使用一个函数读取整个文件内容,并逐行检查和替换
local function doLineClean( cont )
newcont = ''
string.gsub( cont, "(.-)\r?\n", function(line)
if string.match( line, "<integer>.-<%/integer>" ) then
string.gsub( line, "<.->(.-)<.->", function(v)
a, b = string.find(v,"%..*")
if a and b then
v = string.sub( v, 0, a - 1 )
end
line = "\t\t<integer>"..v.."</integer>"
end )
end
newcont = newcont .. line .. '\n'
end )
return newcont
end
本地功能doLineClean(续)
newcont=''
字符串.gsub(续,“(.-)\r?\n”,函数(行)
如果string.match(行“.-”)则
string.gsub(行,(.-)”,函数(v)
a、 b=字符串。查找(v,“%…*”)
如果是a和b,那么
v=string.sub(v,0,a-1)
结束
行=“\t\t”。.v..”
(完)
结束
newcont=newcont..line..'\n'
(完)
返回newcont
结束
我的问题
有没有更高效、更优雅的方法来完成同样的工作?首先,请注意Lua的字符串模式不是完整的正则表达式。它们更有限,功能也更弱,但通常是足够的(如本例所示) 为什么不做一个简单得多的替代品,比如下面的
local s1=[[
3.
3.12
-1.00
-1.99
3.14
]]
本地s2=s1:gsub(“(%-?%d+)%。%d+”,“%1”)
打印(s2)
--> 3
--> 3
--> -1
--> -1
--> 3.14
这发现:
%-?
)%d+
)%。
)%d+
)请注意,如果您可以使用不带前导数字(例如
.99
)或科学符号(例如1.34e7
)的浮点数,则这将不起作用。应该执行以下操作:
s = "<integer>-1.00</integer>"
s:gsub("[.]%d*","")
s=“-1.00”
s:gsub(“[.]%d*”,“”)
要清楚,您不仅希望-1.00
成为-1
,还希望
元素中的所有浮点数都被截断?如果它是-1.99
?@Phrogz yes,截断所有浮点,-1.99
应该是-1
-1,可能此文件在其他不应触摸的位置有十进制值,例如3.14
或1.2.3
。此外,这里的内容还将删除原始句点(例如,“Hello.Bye!”
将变成“Hello-Bye!”
)。解决方案基于给定的输入。我不知道文件中还有什么其他内容。该解决方案需要修改的情况下…感谢逐步解释。