Lua string.match问题?
如何将以下字符串与一个表达式匹配?
local a = "[a 1.001523] <1.7 | [...]> < a123 > < ? 0 ?>";
本地 b =“[b 2.68] <..>”;
局部 c = "[b 2.68] <>";
本地 d = "[b 2.68] <> < > < ?>";
本地名称、netTime、argument1、argument2、argumentX = string:match(?);
-- (字符串是 a 或 b 或 c 或 d)
问题是,字符串可以有不同数量的参数( "<...>" ),并且参数可以有数字、字符、特殊字符或空格它。 我是Lua新手,我必须学习字符串匹配,但我无法在几个小时内学会这一点。我问你,因为我明天需要结果,我真的很感谢你的帮助!
干杯:)
how can I match following strings with one expression?
local a = "[a 1.001523] <1.7 | [...]> < a123 > < ? 0 ?>";
local b = "[b 2.68] <..>";
local c = "[b 2.68] <>";
local d = "[b 2.68] <> < > < ?>";
local name, netTime, argument1, argument2, argumentX = string:match(?);
-- (string is a or b or c or d)
The problem is, the strings can have various counts of arguments( "<...>" ) and the arguments can have numbers, chars, special chars or spaces in it.
I'm new to Lua and I have to learn string matching, but I cannot learn this in a few hours. I ask YOU, because I need the result tomorrow and I really would appreciate your help!
cheers :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Lua 模式非常有限,你不能有替代的表达式,也没有可选的组。因此,这意味着所有参数都需要与相同的表达式匹配,并且如果您只编写单个模式,则需要使用固定数量的参数。查看这个教程,不需要很长时间就能习惯lua模式。
您可能仍然能够使用多种模式解析这些字符串。
^%[(%a+)%s(%d+%.%d+)%]%s
是获取第一部分的最佳方法,假设本地名称可以有多个大写和小写字母。要匹配参数,请对部分输入运行多个模式,例如<%s*>
或<(%w+)>
来单独检查每个参数。或者获取正则表达式库或解析器,这在这里会更有用。
Lua patterns are very limited, you can't have alternative expressions and no optional groups. So that means all of your arguments would need to be matched with the same expressions and you would need to use a fixed amount of arguments if you only write a single pattern. Check this tutorial, it doesn't take long to get used to lua patterns.
You might be still able to parse those strings using multiple patterns.
^%[(%a+)%s(%d+%.%d+)%]%s
is the best you can do to get the first part, assuming local name can have multiple upper and lower case letters. To match the arguments, run multiple patterns on parts of the input, like<%s*>
or<(%w+)>
to check each argument individually.Alternatively get a regex library or a parser, which would be much more useful here.
Lua 模式确实是有限的,但是如果你能做出一些假设,你就可以绕过它。就像如果参数中没有 > 一样,您可以循环遍历所有匹配的 <> :
对于更复杂的事情,你最好使用 LPEG 之类的东西,就像卡佩普说的。
Lua patterns are indeed limited, but you can get around if you can make some assumptions. Like if there will be no >'s in the arguments you could just loop over all matching pairs of <> :
For more complicated things you'll be better of using something like LPEG, like kapep said.