从lua中的一个非常长的字符串中获取随机模式匹配的最快方法是什
发布时间:2020-12-14 21:44:00 所属栏目:大数据 来源:网络整理
导读:我有一个超过200万个字符的字符串,我觉得我目前从模式中找到随机匹配的方式并不快. local function getRandomMatch(string,pattern) local occurenceCount = select(2,string.gsub(string,pattern,"")) local index,randomIndex = 0,math.random(1,occurence
我有一个超过200万个字符的字符串,我觉得我目前从模式中找到随机匹配的方式并不快.
local function getRandomMatch(string,pattern) local occurenceCount = select(2,string.gsub(string,pattern,"")) local index,randomIndex = 0,math.random(1,occurenceCount) for match in string:gmatch(pattern) do index = index + 1 if index == randomIndex then return match end end end 有没有办法可以更快? 解决方法local find,random,match = string.find,math.random,string.match local function getRandomMatch(string,pattern) local pos,random_pos = 0,0 for cnt = 1,math.huge do pos = find(string,pos + 1) if not pos then return match(string,random_pos) elseif random(cnt) == 1 then random_pos = pos end end end for j = 1,20 do print(getRandomMatch("1234","%d%d")) end 更新: local random,match = math.random,string.match local function getRandomMatchFastAndDirty(string,pattern) return match(string,random(#string)) or match(string,pattern) end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |