在 Lua 示例中查找两个字符串文本的"差异"

我正在尝试在 Lua 中找到两个字符串值之间文本的差异,但是我不太确定如何有效地做到这一点。我在使用字符串模式方面缺乏经验,我相信这是我失败的原因。这是一个示例:

-- 原始文本
local text1 = "hello there"
-- 改变的文本
local text2 = "hello.there"

-- 使用某个"模式"找到原始文本的改变
print(text2:match("pattern"))

在上面的示例中,我想输出文本"。",因为那是两个文本之间的差异。对于差异可能敏感于字符串模式的案例,也是如此,例如:

local text1 = "hello there"
local text2 = "hello()there"

print(text2:match("pattern"))

在这个例子中,我想要打印"(",因为在那时新的字符串不再与旧的字符串一致了。

如果有人对此有任何见解,我会非常感激。很抱歉我不能给出更多的代码工作,我不确定从哪里开始。

点赞
用户1847592
用户1847592
local function get_inserted_text(old, new)
   local prv = {}
   for o = 0, #old do
      prv[o] = ""
   end
   for n = 1, #new do
      local nxt = {[0] = new:sub(1, n)}
      local nn = new:sub(n, n)
      for o = 1, #old do
         local result
         if nn == old:sub(o, o) then
            result = prv[o-1]
         else
            result = prv[o]..nn
            if #nxt[o-1] <= #result then
               result = nxt[o-1]
            end
         end
         nxt[o] = result
      end
      prv = nxt
   end
   return prv[#old]
end

用法:

print(get_inserted_text("hello there", "hello.there"))    -->  .
print(get_inserted_text("hello there", "hello()there"))   -->  ()
print(get_inserted_text("hello there", "hello htere"))    -->  h
print(get_inserted_text("hello there", "heLlloU theAre")) -->  LUA
2017-01-06 20:55:00
用户3979429
用户3979429

只需迭代字符串并找出它们不匹配的位置。

function StringDifference(str1,str2)
    for i = 1,#str1 do --循环字符串
        if str1:sub(i,i) ~= str2:sub(i,i) then --如果该字符不等于它的对应字符
            return i --返回该索引
        end
    end
    return #str1+1 --返回较短的字符串结束后的索引作为备用。
end

print(StringDifference("hello there", "hello.there"))
2017-01-06 23:18:29