lua string

lua string.find

local s=[[{"weatherinfo":{"city":"石家庄","city_en":"shijiazhuang","date_y":"2012年4月24日","date":"","week":"星期二","fchh":"11","cityid":"101090101","temp1":"18℃~12℃","temp2":"22℃~12℃","temp3":"24℃~13℃","temp4":"26℃~15℃","temp5":"25℃~14℃","temp6":"25℃~15℃","weather1":"小雨转阴","weather2":"晴","weather3":"晴","weather4":"晴转多云","weather5":"多云","weather6":"多云"}}]]
function j(t)
	local a,b=string.find(s,"""..t.."":")
	print(a,b)
	local c,d=string.find(s,"%b""",b)
	print(c,d)
	return(string.sub(s,c+1,d-1))
end
print(j('city'))

17 23
24 31
石家庄

lua string

进入主题,话说,有形如
&&123&&456&这样的字符串
我想修改其中一个&位置之前的数据,比如:
1,用789替换第1个&之前的数据
结果为:789&&123&&456&
2,用789替换第3个&之前的数据
结果为:&&789&&456&
3,用789替换第10个&之前的数据
结果为:因为没有第10个&, 保留原来的字符串&&123&&456&
要点:每个&为一个分隔符,如果有数据就写在&的前面,没有数据就留空。
所以&&&&&&&也是一个合法的输入

-- lua 5.1.4
function mysub(str, sep, n)
local i = 0
return str:gsub(".-" .. sep, function () 
i = i + 1
if (i == n) then return "789" .. sep end
end
)
end
str = "&&123&&456&"
sep = '&'
--for n = 1, 11, 2 do
for _, n in ipairs({1, 3, 10}) do 
local ss = mysub(str, sep, n)
print(ss)
end
print(mysub("&&&&&",sep,2))


 

原文地址:https://www.cnblogs.com/byfei/p/6389906.html