Lua: %b with modifiers

2019-08-29 03:43发布

问题:

I'm trying to match a string that contains Lua code.

a = [[workspace.Object["Child"]:remove()]]

to do this, I'm trying to create an option where either .x or ['x'] would be matched regardless of what order they are in or how many of them there are.

A couple problems I have run into:

  • How do I match more than one combined character/pattern between brackets? [abc] matches a or b or c, but not abc.
  • How do I add a modifier to %b[]? ex. %b[]+ to match ['x']['x']['x']
  • If I could match something like %[.-%] *, that would work the same.

回答1:

Lua does not fully support regexps.
But you can do your task step-by-step, using intermediate strings.

local str0 = [[workspace.Object["Child"]['xx'][5].xxx:remove()]]
local str = str0
   :gsub('%b[]',
      function(s)
         return s:gsub('^%[%s*([\'"]?)(.*)%1%s*%]$','{%2}')
      end
   )
   :gsub('[%.:]%s*([%w_]+)','{%1}')

print(str0)
print(str)
print()
for w in str:gmatch'{(.-)}' do
   print(w)
end

---------------------------
-- output
---------------------------
workspace.Object["Child"]['xx'][5].xxx:remove()
workspace{Object}{Child}{xx}{5}{xxx}{remove}()

Object
Child
xx
5
xxx
remove

EDIT :

local str0 = [[workspace.Object["Child"]['xx'][5][ [=[xxx]=] ]:remove()]]
local str = str0
   :gsub('%b[]',
      function(s)
         return s:gsub('^%[%s*([\'"]?).*%1%s*%]$','{%0}')
      end
   )
   :gsub('%.%s*[%w_]+','{%0}')
   :gsub(':%s*[%w_]+%s*([\'"]).-%1','{%0}')
   :gsub(':%s*[%w_]+%s*%b()','{%0}')
   :gsub('{(:%s*remove%s*%(%s*%))}','%1')
   :gsub('}%s*{', '')
   :gsub('([%w_]+)%s*(%b{})%s*:%s*remove%s*%(%s*%)',
      function(s1, s2)
         return 'removefilter('..s1..s2:match'^{(.*)}$'..')'
      end
   )
   :gsub('([%w_]+)%s*:%s*remove%s*%(%s*%)','removefilter(%1)')
   :gsub('[{}]', '')

print(str0)
print(str)

---------------------------
-- output
---------------------------
workspace.Object["Child"]['xx'][5][ [=[xxx]=] ]:remove()
removefilter(workspace.Object["Child"]['xx'][5][ [=[xxx]=] ])