Lua - 检查字符串中的重复数据

我收到的输入为以下字符串数据:

"route1,1234,1,no~,,route2,1234,1,no~,"

它代表两个“记录”……每个记录有4个字段。 我已构建代码,将此字符串解析为其各个列/字段。 但是,测试是否有任何字段2中的重复项时无法正常工作。字段2是当前值为“1234”的字段。

以下是代码:

  local result = { }
  local from = 1
  local delim_from, delim_to = string.find( self, delimiter, from )
  while delim_from do
    table.insert( result, string.sub( self, from , delim_from-1 ) )
    from = delim_to + 1
    delim_from, delim_to = string.find( self, delimiter, from )
  end
  table.insert( result, string.sub( self, from ) )
  return result
end

local check_for_duplicate_entries = function(route_data)
      local route
      local route_detail = {}
      local result =true
      local errtxt
      local duplicate = false

print("received :" ..route_data)
      route = string.gsub(route_data, "~,,", "~")
      route = route:sub(1,string.len(route)-2)
print("route :" ..route)

      -- break up in to an array
      route = string.split(route,"~")

      for key, value in pairs(route) do
            route_detail[key] = string.split(value,",")
      end

      local list_of_second_column_only = {}
      for key,value in pairs(route_detail) do
         local temp = value[2]
         print(temp .. " - is the value I'm checking for")
         if list_of_second_column_only[temp] == nil then
            print("i dont think it exists")
            list_of_second_column_only[key] = value[2]
            print(list_of_second_column_only[key])
         else
            --found a duplicate.
            return true
         end
      end
      return false
end

print(check_for_duplicate_entries("route1,1234,1,no~,,route2,1234,1,no~,"))

我认为我出错的地方是测试:

 if list_of_second_column_only[temp] == nil then

我认为我正在检查值为temp而不是包含temp值的值的键。但是,我不知道如何修复语法。 另外,我想知道是否有更有效的方法来实现此目的。我接收到的“记录”数量是动态/未知的,每个记录的第二列的值也是。

谢谢。

点赞
用户2279620
用户2279620

尝试一下。它检查第二个字段的值。

我没有考虑效率。

如果list_of_second_column_only[value [2]] == nil then
    print("我认为它不存在")
    list_of_second_column_only[value [2]] = true
    print(list_of_second_column_only[value [2]])
否则
    --找到了重复。
    返回真
端
2013-10-01 18:19:59
用户2279620
用户2279620

这将更加高效,仅需创建一个表并减少正则表达式匹配。

match需要确保你只对第二个字段中的重复项感兴趣。

local function check_for_duplicate_entries(route_data)
    assert(type(route_data)=="string")
    local field_set = {}
    for route in route_data:gmatch"([^~]*)~,?,?" do
        local field = route:match",([^,]*)"
        if field_set[field] then
            return true
        else
            field_set[field] = true
        end
    end
    return false
end
2013-10-01 18:36:53