开发者

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

开发者 https://www.devze.com 2023-03-02 18:17 出处:网络
I want to write a regular expression that is equivalent to the following Javascript regexp: /^(\\(\\))?$/

I want to write a regular expression that is equivalent to the following Javascript regexp:

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

I cannot find an equivalent representation in Lua. The problem I had was I could make multiple characters followed by "?".

For example,

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

^%(%)?$ can be used t开发者_JAVA百科o match out "(" and "()"

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


As you've discovered, the ? modifier in Lua's pattern language applies only to a single character class. Instead of using patterns/regexes for this, how about something simpler: foo == '()' or foo == ''? Or is your real problem something more complex? If it is, please tell us what you're really trying to do.


You can use LPeg (a pattern-matching library for 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("()") )
0

精彩评论

暂无评论...
验证码 换一张
取 消