2014-12-03 35 views
1

刪除它,我得到以下格式的字符串:查找在Lua模式的第一個實例,並從字符串

abc:321,cba:doodoo,hello:world,eat:mysh0rts 

我想從字符串獲取數據配對的一個實例,從中刪除字符串,因此,例如,如果我想抓住以下hello:world的價值,我想這樣的事情發生:

local helloValue, remainingString = GetValue("hello") 

將返回worldhellovalueabc:321,cba:doodoo,eat:mysh0rtsremainingString

我這樣做很麻煩與循環,有什麼更好的方式呢?

+0

這是更好地展示自己在做什麼,讓我們知道如何改進。 – 2014-12-03 06:06:21

+0

如果輸入是'abc:321,cba:doodoo,eat:mysh0rts,hello:world',那麼你的期望輸出是什麼? – 2014-12-03 06:11:38

回答

0
(hello:[^,]+,) 

只是做empty string .The替換數據和$1你want.See演示的東西代替。

http://regex101.com/r/yR3mM3/24

+1

這個問題被錯誤地標記爲**正則表達式**,Lua模式不是正則表達式,所以這不起作用。 – 2014-12-03 06:07:17

2

這是一種方式:

local str = 'abc:321,cba:doodoo,hello:world,eat:mysh0rts' 

local t = {} 
for k, v in str:gmatch('(%w+):(%w+)') do 
    if k ~= 'hello' then 
     table.insert(t, k .. ':' .. v) 
    else 
     helloValue = v 
    end 
end 

remainingString = table.concat(t, ',') 
print(helloValue, remainingString) 

你可以把這個向更多普通GetValue功能自己。

1

嘗試也是這樣:

local str = 'abc:321,cba:doodoo,hello:world,eat:mysh0rts' 

function GetValue(s,k) 
    local p=k..":([^,]+),?" 
    local a=s:match(p) 
    local b=s:gsub(p,"") 
    return a,b 
end 

print(GetValue(str,"hello")) 
print(GetValue(str,"eat")) 

如果要分析整個字符串轉換成鍵值對,試試這個:

for k,v in str:gmatch("(.-):([^,]+),?") do 
    print(k,v) 
end 
相關問題