如何在Lua多行字符串中匹配行首的#序列?
如何在Lua中匹配多行字符串里任意行首的#序列?
问题描述
需要匹配多行字符串中任意行开头的连续#序列,具体示例如下:
- 示例1:字符串
local mystr = "##First line\nSecond line\nThird line",需匹配出## - 示例2:字符串
local mystr = "First line\nSecond line\n### Third line",需匹配出### - 示例3:字符串
local mystr = "First line\nSecond line\nThird line",无匹配结果
原本尝试使用模式^(%#+),但Lua中的^仅锚定整个字符串的开头,而非每行的开头,因此需要实现针对行首的匹配逻辑。
解决方案
Lua的原生模式匹配不支持多行模式,但可以通过以下两种方式实现需求:
方法1:分割字符串后逐行匹配
先将多行字符串按换行符分割为单独的行,再对每一行使用^(%#+)匹配行首的#序列:
local function get_line_hashes(str) local results = {} -- 遍历每一行 for line in string.gmatch(str, "[^\n]+") do local hashes = line:match("^(%#+)" if hashes then table.insert(results, hashes) end end return results end -- 测试示例1 local str1 = "##First line\nSecond line\nThird line" print(table.concat(get_line_hashes(str1), ", ")) -- 输出: ## -- 测试示例2 local str2 = "First line\nSecond line\n### Third line" print(table.concat(get_line_hashes(str2), ", ")) -- 输出: ### -- 测试示例3 local str3 = "First line\nSecond line\nThird line" print(table.concat(get_line_hashes(str3), ", ")) -- 输出空字符串
方法2:构造覆盖行首的匹配模式
直接构造模式,同时匹配字符串开头或换行符后的位置,再捕获后续的连续#:
local function get_line_hashes(str) local results = {} -- 模式解释:匹配(字符串开头/换行符)后的连续#,捕获#序列 for _, hashes in string.gmatch(str, "(^|\n)(%#+)" do table.insert(results, hashes) end return results end -- 测试效果与方法1完全一致
内容的提问来源于stack exchange,提问作者sdbbs
相关产品推荐
相关产品推荐

