转义序列无效 lua 正则表达式
Invalid escape sequence lua regex
我写了一个正则表达式来匹配下面的字符串类型,当我在正则表达式匹配器中在线检查它时,它按预期工作 -
"['432', '212']"
regex - "(\[)('([^']|'')*'), ('([^']|'')*')(])"
ngx.re.find(string, "\"(\[)('([^']|'')*'), ('([^']|'')*')(])\"", "jo")
当我在 lua 块中使用它来匹配字符串时,它给我无效的转义序列错误。
我转义了双引号并尝试转义正则表达式中的特殊字符以及 \ 但问题仍然存在。任何指针都会有所帮助。谢谢!
我个人更喜欢为最简单的模式编写解析器。它比 Regex 灵活得多,即使它变大也能保持可读性。下面我展示了一个解析器,用于使用 LPEG.
匹配的表达式
您可以在这里找到一个很好的 LPEG 教程:http://leafo.net/guides/parsing-expression-grammars.html
local lpeg = assert(require("lpeg"))
local C, Ct, P, R, S = lpeg.C, lpeg.Ct, lpeg.P, lpeg.R, lpeg.S
-- optional whitespace (zero or more)
local ws = S" \n\r\t"^0
-- quoted integer, converted to number
local quot = P"'" * C(R"09"^1) / tonumber * P"'"
-- integer followed by zero or more commas followed by integer
local list = quot * ws * (P"," * ws * quot)^0
-- [ followed by list of integers captured in a table followed by ]
local rule = P"[" * ws * Ct(list) * ws * P"]"
-- match the string and collect results
local nums = rule:match("['432', '212']")
-- print result table
print(table.concat(nums,","))
$ lua test.lua
432,212
我会重申人们在评论中所说的话。您在正则表达式中使用了 \[
,这是一个带引号的字符串。在带引号的字符串中,反斜杠开始一个转义序列,但是 \[
是一个无效的转义序列(请参阅 the Lua 5.1 manual 以了解有效的转义序列),因此 Lua 解析器会抱怨它。 Vanilla Lua 5.1 只是删除了反斜杠(这在这个正则表达式中会很糟糕),而 Lua 5.3 和 LuaJIT 对此表示不满。
您可以删除解析错误,并通过使用另一个反斜杠转义它来确保反斜杠实际插入到字符串中 – "\["
– 正如您在 JavaScript 中使用时必须做的那样RegExp
constructor,或使用不解释转义序列的长字符串 – [[\[]]
。如果您使用长字符串,您还必须将正则表达式中的转义双引号 \"
替换为普通的 "
.
我写了一个正则表达式来匹配下面的字符串类型,当我在正则表达式匹配器中在线检查它时,它按预期工作 -
"['432', '212']"
regex - "(\[)('([^']|'')*'), ('([^']|'')*')(])"
ngx.re.find(string, "\"(\[)('([^']|'')*'), ('([^']|'')*')(])\"", "jo")
当我在 lua 块中使用它来匹配字符串时,它给我无效的转义序列错误。 我转义了双引号并尝试转义正则表达式中的特殊字符以及 \ 但问题仍然存在。任何指针都会有所帮助。谢谢!
我个人更喜欢为最简单的模式编写解析器。它比 Regex 灵活得多,即使它变大也能保持可读性。下面我展示了一个解析器,用于使用 LPEG.
匹配的表达式您可以在这里找到一个很好的 LPEG 教程:http://leafo.net/guides/parsing-expression-grammars.html
local lpeg = assert(require("lpeg"))
local C, Ct, P, R, S = lpeg.C, lpeg.Ct, lpeg.P, lpeg.R, lpeg.S
-- optional whitespace (zero or more)
local ws = S" \n\r\t"^0
-- quoted integer, converted to number
local quot = P"'" * C(R"09"^1) / tonumber * P"'"
-- integer followed by zero or more commas followed by integer
local list = quot * ws * (P"," * ws * quot)^0
-- [ followed by list of integers captured in a table followed by ]
local rule = P"[" * ws * Ct(list) * ws * P"]"
-- match the string and collect results
local nums = rule:match("['432', '212']")
-- print result table
print(table.concat(nums,","))
$ lua test.lua
432,212
我会重申人们在评论中所说的话。您在正则表达式中使用了 \[
,这是一个带引号的字符串。在带引号的字符串中,反斜杠开始一个转义序列,但是 \[
是一个无效的转义序列(请参阅 the Lua 5.1 manual 以了解有效的转义序列),因此 Lua 解析器会抱怨它。 Vanilla Lua 5.1 只是删除了反斜杠(这在这个正则表达式中会很糟糕),而 Lua 5.3 和 LuaJIT 对此表示不满。
您可以删除解析错误,并通过使用另一个反斜杠转义它来确保反斜杠实际插入到字符串中 – "\["
– 正如您在 JavaScript 中使用时必须做的那样RegExp
constructor,或使用不解释转义序列的长字符串 – [[\[]]
。如果您使用长字符串,您还必须将正则表达式中的转义双引号 \"
替换为普通的 "
.