Lua字符串匹配出现问题?

如何用一个表达式匹配以下字符串?

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(?);

--(字符串为a、b、c或d)

问题是,这些字符串中的参数(“<...>”)可以有各种计数,并且参数中可以包含数字、字符、特殊字符或空格。我对Lua还不熟悉,我必须学习字符串匹配,但我无法在几个小时内学习到。我向你求助,因为我需要在明天得到结果,我真的很感激你的帮助!

干杯 :)

原文链接 https://stackoverflow.com/questions/7220973

点赞
stackoverflow用户897024
stackoverflow用户897024

Lua模式非常有限,不能有替代表达式和可选组。这意味着如果你只写一个模式,所有的参数都需要与相同的表达式匹配,你需要使用固定数量的参数。查看这个教程,你很快就会习惯Lua模式。

你可能仍然可以使用多个模式来解析这些字符串。 ^%(%a +)%s(%d + \。%d +)%]%s是获取第一部分的最佳方法,假设_local name_可以有多个大写和小写字母。要匹配参数,对输入的部分运行多个模式,例如<%s * %>或<(%w +)>以逐个检查每个参数。

或者获得一个正则表达式库或解析器,在这里会更有用。

2011-08-28 13:49:04
stackoverflow用户513763
stackoverflow用户513763

Lua 的模式确实有限,但如果你能做出一些假设,就可以绕过限制。例如,如果参数中不会有 >,那么你可以循环处理所有匹配的 <>

local a = "[a 1.001523] <1.7 | [...]> < a123 > < ? 0 ?>"
local b = "[b 2.68] <..>"
local c = "[b 2.68] <>"
local d = "[b 2.68] <> < > < ?>"

function parse(str)
    local name,nettime,lastPos = str:match'%[(%a+)%s(%d+%.%d+)%]()'
    local arguments={}
    -- start looking for arguments only after the initial part in [ ]
    for argument in str:sub(lastPos+1):gmatch('(%b<>)') do
        argument=argument:sub(2,-2) -- strip <>
        -- do whatever you need with the argument. Here we'll just put it in a table
        arguments[#arguments+1]=argument
    end
    return name,nettime,unpack(arguments)
end

如果需要处理更复杂的情况,最好使用像 LPEG 这样的工具,正如 kapep 所说的那样。

2011-08-29 11:56:28