Lua中的%b带修饰符。

我尝试匹配包含 Lua 代码的字符串。

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

为此,我正试图创建一个选项,在其中 .x['x'] 将被匹配,无论它们的顺序或数量如何。

我遇到了几个问题:

  • 如何在方括号之间匹配更多的组合字符/模式?[abc] 匹配 abc,但不匹配 abc
  • 如何向 %b[] 添加修饰符?例如 %b[]+ 匹配 ['x']['x']['x']
  • 如果我能匹配类似于 %[.-%] * 的东西,那将起着相同的作用。
点赞
用户1847592
用户1847592

Lua 并不完全支持正则表达式。

但您可以逐步完成您的任务,使用中间字符串。

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]=] ])
2013-02-27 19:21:38