【问题标题】:Lua remove characters from leftLua从左边删除字符
【发布时间】:2016-03-16 04:40:12
【问题描述】:

我是 lua 新手,我正在尝试从拆分字符串的右侧提取值。我有这个:

local t ={}
local data = ("ret=OK,type=aircon,reg=eu,dst=1,ver=2_2_5,pow=1,err=0,location=0,name=,icon=0,method=home only,port=30050,id=,pw=,lpw_flag=0,adp_kind=2,pv=0,cpv=0,led=1,en_setzone=1,mac=FCDBB382E70B,adp_mode=run")
for word in string.gmatch(data, '([^,]+)') do
    t[#t + 1] = word
end
local first = t[1]:gsub("%s+", "")

这给了我字符串“ret=OK”。 我该怎么做才能从这个字符串中只得到“OK”,比如:从等号右侧获取所有内容并将其和左侧部分删除。我必须对“数据”变量中的所有字符串执行此操作。谢谢。

【问题讨论】:

标签: string lua


【解决方案1】:

我会推荐以下内容:

local data = 'ret=OK,type=aircon,reg=eu,dst=1,ver=2_2_5,pow=1,err=0,location=0,name=,icon=0,method=home only,port=30050,id=,pw=,lpw_flag=0,adp_kind=2,pv=0,cpv=0,led=1,en_setzone=1,mac=FCDBB382E70B,adp_mode=run'

local t = {}
for key, val in string.gmatch(data, '([^=,]*)=([^=,]*),?') do
  t[key] = val
end

print(t['ret'])  -- prints "OK"
print(t['adp_mode'])  -- prints "run"

请注意,lua 模式使尾随逗号可选(否则您会错过列表中的最后一个密钥对)。

【讨论】:

    【解决方案2】:

    试试这个

    for key, val in string.gmatch(data, "(%W*)=(%W*),") do
       print(key.." equals "..val)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      相关资源
      最近更新 更多