如何在Lua中检测字段是否包含字符

我正在尝试修改现有的lua脚本,以清理Aegisub中的字幕数据。

我想添加删除包含符号"♪"的行的能力。

以下是我要修改的代码:

-- 删除已注释或空行
function noemptycom(subs,sel)
    progress("正在删除已注释/空行")
    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知识的人来说,最简单的方法是什么?

点赞
用户2858170
用户2858170

in 只在通用的 for 循环中使用。你的 if line.text in (♪) then 不是有效的 Lua 语法。

可以这样写:

if line.comment or line.text == "" or line.text:find("\u{266A}") then

就可以正常运行了。

2021-04-13 11:55:11
用户11740758
用户11740758

在 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

-- 输出
-- Replaced     1   times, changed to:  Text with strange notation sign in text

最后,我们只是检测,没有进行更改...

local str,rc=('Text with strange ♪ sign in text'):gsub('(♪)','%1')

if rc~=0 then
 print('Found ',rc,'times, Text is: ',str)
end
-- 输出是...
-- Found    1   times, Text is:     Text with strange ♪ sign in text

%1 保存了 '(♪)' 找到的内容。

所以 ♪ 被替换为 ♪

只有 rc 用作后续处理的条件。

2021-04-13 18:04:20