使用string.match获取最后一次出现的Lua模式

时间:2014-05-01 02:51:54

标签: lua pattern-matching lua-patterns last-occurrence

使用Lua我正在使用模式解析大型XML字符串中最后一次出现的XML标记:

local firstPattern = "<tag>(.-)</tag>"

然后我使用以下代码查找每个事件:

local lastMatch
for match in string.gmatch(xmlString, firstPattern) do
  lastMatch = match
end

它似乎不是很快,所以我尝试在我的模式的开头添加一个贪婪的角色:

local secondPattern = ".*<tag>(.-)</tag>"
lastMatch = string.match(xmlString, secondPattern)

在解析之前和之后打印os.clock()我发现第二个模式稍微快一点,但我不得不认为有一个更好的模式来匹配最后一次出现的xml标记。

我还尝试了第三种模式,但它只返回xml标记的第一个实例。

local thirdPattern = "<tag>(.-)</tag>.-$"
local firstMatch = string.match(xmlString, thirdPattern)

0 个答案:

没有答案
相关问题