一个简单的滚动你自己的方法(基于模式保持相同长度的假设):
function hammingdistance(a,b)
local ta={a:byte(1,-1)}
local tb={b:byte(1,-1)}
local res = 0
for k=1,#a do
if ta[k]~=tb[k] then
res=res+1
end
end
print(a,b,res) -- debugging/demonstration print
return res
end
function fuz(s,pat)
local best_match=10000
local best_location
for k=1,#s-#pat+1 do
local cur_diff=hammingdistance(s:sub(k,k+#pat-1),pat)
if cur_diff < best_match then
best_location = k
best_match = cur_diff
end
end
local start,ending = math.max(1,best_location),math.min(best_location+#pat-1,#s)
return start,ending,s:sub(start,ending)
end
s=[[Hello, Universe! UnIvErSe]]
print(fuz(s,'universe'))
免责声明:不推荐,仅供娱乐:
如果你想要更好的语法(而且你不介意弄乱标准类型的元表),你可以使用这个:
getmetatable('').__sub=hammingdistance
a='Hello'
b='hello'
print(a-b)
但请注意 a-b 这样不等于 b-a。