Lua脚本识别多行$$标签文本块异常问题求助
Lua脚本识别多行
$$文本块的问题解决 问题描述
我需要编写脚本识别文件中位于$$标签内的文本块,文件内容可能是单行形式:
$$ some text $$
或多行形式:
$$ some text $$
原Lua脚本处理单行形式正常,但处理多行形式时,print("text between $$ detected")会执行两次,且无法正确捕获整个文本块内容。
原脚本代码:
function file_exists(name) local f = io.open(name, "r") if f ~= nil then io.close(f) return true else return false end end function rows_from(file) if not file_exists(file) then return {} end local rows = {} for line in io.lines(file) do rows[#rows + 1] = line end return rows end function detect_non_indexed_equations(rows,j) if rows[j]:sub(1,2) == "$$" then for i=j, #rows do if rows[i]:sub(-2) == "$$" then print("text between $$ detected") break end end end end function fetch_equations(start) local rows = rows_from(file) for j = start, #rows do detect_non_indexed_equations(rows,j) end end fetch_equations(1)
问题原因
原脚本逐行检查每行开头是否为$$,多行形式中结尾的$$所在行(仅含$$)会被再次判定为块的起始,导致重复触发打印逻辑。同时原脚本仅做检测提示,未实现文本块内容的捕获。
解决思路
采用状态机模式跟踪当前是否处于$$块内部:
- 用
in_block变量标记状态,默认false表示不在块内 - 遍历每行时,根据当前状态和行内容切换状态,同时记录块的起始/结束位置
- 退出块时一次性捕获整个文本块内容,避免重复检测
修改后的脚本
function file_exists(name) local f = io.open(name, "r") if f ~= nil then io.close(f) return true else return false end end function rows_from(file) if not file_exists(file) then return {} end local rows = {} for line in io.lines(file) do rows[#rows + 1] = line end return rows end function detect_non_indexed_equations(rows) local in_block = false local block_start = nil local equations = {} for i, line in ipairs(rows) do -- 进入$$块 if not in_block and line:sub(1,2) == "$$" then in_block = true block_start = i + 1 -- 跳过起始$$行,记录内容起始位置 print("开始识别$$文本块") -- 退出$$块 elseif in_block and line:sub(-2) == "$$" then in_block = false -- 捕获块内内容 local block_content = {} for j = block_start, i - 1 do table.insert(block_content, rows[j]) end table.insert(equations, block_content) print("$$文本块识别完成,内容行数:" .. #block_content) print("块内容:") for _, content_line in ipairs(block_content) do print(" " .. content_line) end end end return equations end function fetch_equations(file) local rows = rows_from(file) return detect_non_indexed_equations(rows) end -- 替换为你的目标文件名 local target_file = "your_file.txt" local detected_equations = fetch_equations(target_file)
改动说明
- 新增
in_block状态变量,避免重复触发块检测逻辑 - 记录
block_start标记内容起始行,退出块时一次性捕获完整文本 - 将检测结果存储到
equations表中,方便后续业务处理 - 修复多行块重复打印问题,每个块仅触发一次完成提示
内容的提问来源于stack exchange,提问作者user3204810
相关产品推荐
相关产品推荐

