如何解决Lua中如何检测一个字段是否包含一个字符
我正在尝试修改现有的用于清理 Aegisub 中字幕数据的 lua 脚本。
我想添加删除包含符号“♪”的行的功能
这是我要修改的代码:
-- delete commented or empty lines
function noemptycom(subs,sel)
progress("Deleting commented/empty lines")
noecom_sel={}
for s=#sel,1,-1 do
line=subs[sel[s]]
if line.comment or line.text=="" then
for z,i in ipairs(noecom_sel) do noecom_sel[z]=i-1 end
subs.delete(sel[s])
else
table.insert(noecom_sel,sel[s])
end
end
return noecom_sel
end
我真的不知道我在这里做什么,但我知道一些 SQL 和 LUA 显然也使用了 IN 关键字,所以我尝试将 IF 行修改为这个
if line.text in (♪) then
不用说,它没有用。在 LUA 中有没有一种简单的方法可以做到这一点?我看过一些关于 string.match() 和 string.find() 函数的帖子,但我不知道从哪里开始尝试将这些代码放在一起。对于 Lua 零知识的人来说,最简单的方法是什么?
解决方法
in
仅用于通用 for 循环。您的 if line.text in (♪) then
不是有效的 Lua 语法。
类似的东西
if line.comment or line.text == "" or line.text:find("\u{266A}") then
应该可以。
,在 Lua 中,每个字符串都有 string
函数作为附加方法。
因此,在循环中的字符串变量上使用 gsub()
,例如...
('Text with ♪ sign in text'):gsub('(♪)','note')
...替换符号,输出是...
Text with note sign in text
...不是用 'note' 替换它,而是一个空的 '' 删除它。gsub()
返回 2 个值。
第一:有无变化的字符串
第二个:表示模式匹配频率的数字
所以第二个返回值可用于条件或成功。
( 0 代表“找不到模式”)
所以让我们检查上面...
local str,rc=('Text with strange ♪ sign in text'):gsub('(♪)','notation')
if rc~=0 then
print('Replaced ',rc,'times,changed to: ',str)
end
-- output
-- Replaced 1 times,changed to: Text with strange notation sign in text
最后只检测,不做任何改变...
local str,'%1')
if rc~=0 then
print('Found ',Text is: ',str)
end
-- output is...
-- Found 1 times,Text is: Text with strange ♪ sign in text
%1
保存 '(♪)'
找到的内容。
所以 ♪
被替换为 ♪
。
并且只有 rc
用作进一步处理的条件。