如何在Lua中编写一个等效于JavaScript中/(\(\))?$/的正则表达式?

我想写一个等价于以下 Javascript 正则表达式的正则表达式:

/^(\(\))?$/

以匹配 "()" 和 ""

我找不到 Lua 中的等价表示。我的问题是我可以使用多个字符后跟 "?"。

例如,

^%(%)$ 可用于匹配 "()"

^%(%)?$ 可用于匹配 "(" 和 "()"

^(%(%))?$ 不起作用。

原文链接 https://stackoverflow.com/questions/5891958

点赞
stackoverflow用户4323
stackoverflow用户4323

正如你所发现的那样,在 Lua 的模式语言中,? 修饰符仅适用于单个字符类。不要使用模式/正则表达式,尝试使用更简单的东西:foo == '()' or foo == ''。或者你真正的问题更复杂吗?如果是,请告诉我们你真正想做什么。

2011-05-05 02:33:57
stackoverflow用户88888888
stackoverflow用户88888888

你可以使用 LPeg (一个用于 Lua 的模式匹配库)。

local lpeg = require "lpeg"

-- this pattern is equivalent to regex: /^(\(\))?$/
-- which matches an empty string or open-close parens
local p = lpeg.P("()") ^ -1 * -1

-- p:match() returns the index of the first character
-- after the match (or nil if no match)
print( p:match("()") )
2011-05-05 07:26:25