正则表达式在 Lua 中不起作用

我无法使我的正则表达式在 Lua 中起作用。我已经在其他环境中进行了测试,如我的文本编辑器和一些在线正则表达式工具,它在那里似乎工作正常。

在其他环境中正常工作的正则表达式:

RAY\.decrypt\s*\(([\"\'].+?(?=[\"\']).+?(?=[\)]))\s*\)

我在 Lua 中尝试使用的正则表达式(只替换了\为%'s)

RAY%.decrypt%s*%(([\"\'].+?(?=[\"\']).+?(?=[%)]))%s*%)

我尝试匹配的示例文本(我想捕获括号中的内容)

RAY.decrypt ("\x02\x02\x02\x02\x02\x02\x02\x02")
RAY.decrypt ("\xd6E\xd6E\xd6E\xd6E\xd6E")
RAY.decrypt("\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e")

其他工具都能匹配文本并捕获我想要的内容,但我很难让 Lua 实现它,因为它没有匹配任何内容。

local s = [[RAY.decrypt ("\x02\x02\x02\x02\x02\x02\x02\x02")
RAY.decrypt ("\xd6E\xd6E\xd6E\xd6E\xd6E")
RAY.decrypt("\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e")]]

print(string.find(s, "RAY%.decrypt%s*%(([\"\'].+?(?=[\"\']).+?(?=[%)]))%s*%)"))
> nil

如果有帮助,谢谢!

点赞
用户2459026
用户2459026

我完全不了解 LUA,但维基百科关于 LUA 正则表达式引擎的描述是:

"使用简化的、有限制的语言;可以绑定到更强大的库中,比如 PCRE 或者像 LPeg 这样的替代解析器。"

因此,你要么将其绑定到 PCRE,要么不要与其他引擎进行比较,只需使用 LUA 文档为 LUA 编写正则表达式,而不是使用你的文本编辑器。

2017-10-08 07:29:02
用户1847592
用户1847592
local s = [[
RAY.decrypt ("\x02\x02\x02\x02\x02\x02\x02\x02")
RAY.decrypt ('\xd6E\xd6E\xd6E\xd6E\xd6E')
RAY.decrypt( "\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e" )
]]

for w in s:gmatch"RAY%.decrypt%s*%(%s*(([\"']).-%2)%s*%)" do
   print(w)
end

输出:

"\x02\x02\x02\x02\x02\x02\x02\x02"
'\xd6E\xd6E\xd6E\xd6E\xd6E'
"\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e"
2017-10-08 07:59:36
用户107090
用户107090

Lua的标准字符串库不支持完整的正则表达式,但其模式匹配非常强大。

此脚本匹配括号中的所有内容:

for w in s:gmatch("%((.-)%)") do
   print(w)
end
2017-10-08 11:43:38
用户8760363
用户8760363

Lua 内置的 "regex" 被称为 "patterns"

这匹配括号中的内容

local source = [[
  RAY.decrypt ("\x02\x02\x02\x02\x02\x02\x02\x02")
  RAY.decrypt ("\xd6E\xd6E\xd6E\xd6E\xd6E")
  RAY.decrypt("\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e")
]]

-- 这捕获包含 RAY.decrypt("...") 的表达式
for content in string.gmatch(source , "RAY%.decrypt%s*%(%s*\"(.-)\"%s*%)") do
   print(content)
end

-- 这捕获双引号内的表达式
for content in string.gmatch(source , "\"(.-)\"") do
   print(content)
end

-- 这捕获单引号或双引号内的表达式,例如 RAY.decrypt('\x8e\x8e\x8e\x8e\x8e\x8e\x8e\x8e')
for content in string.gmatch(source , "[\"'](.-)[\"']") do
   print(content)
end

-- 这捕获括号内的表达式(将捕获引号)
for content in string.gmatch(source , "%((.-)%)") do
   print(content)
end
2017-10-11 16:34:03