How to write a regular expression in Lua that is equivalent to / (\ (\))? $ / In js

I want to write a regex equivalent to the following Javascript regexp:

/^(\(\))?$/ to match "()" and ""

I cannot find an equivalent representation in Lua. The problem was that I could make a few characters followed by "?".

For instance,

^%(%)$ can be used to match "()"

^%(%)?$ can be used to match "(" and "()"

but ^(%(%))?$does not work.

+3
source share
2 answers

, ? Lua . /regexes , - : foo == '()' or foo == ''? - ? , , .

+3

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("()") )
+2

All Articles