从Lua </string>中的“<string>”中取出字符串

时间:2013-12-12 05:21:04

标签: string parsing lua lua-patterns

我想解析Lua中字符串中的一些数据。我尝试了string.matchstring.sub的几种组合,但没有运气。这是细节...

str='[{id:78749,name:Hrithik Roshan,character:Vijay Deenanath Chauhan,order:0,cast_id:1,profile_path:/1uGhDRNCA9I4WvyD9TfgKYnLEhZ.jpg},{id:77234,name:Priyanka Chopra,character:Kaali Gawde,ord'

fixstr = string.gsub(str,"name:","<actors>")
fixstr = string.gsub(fixstr,"character:","<actors>")
print(fixstr)
fixstr1 = string.match( fixstr, "<actors>(.+)<actors>")
print(fixstr1)

输出:

rint(fixstr)

的输出
[{id:78749,<actors>Hrithik Roshan,<actors>Vijay Deenanath Chauhan,order:0,cast_id:1,profile_path:/1uGhDRNCA9I4WvyD9TfgKYnLEhZ.jpg},{id:77234,<actors>Priyanka Chopra,<actors>Kaali Gawde,ord

print(fixstr1)

的输出
Hrithik Roshan,<actors>Vijay Deenanath Chauhan,order:0,cast_id:1,profile_path:/1uGhDRNCA9I4WvyD9TfgKYnLEhZ.jpg},{id:77234,<actors>Priyanka Chopra,

我要做的是获取<actors>...<actors>之间的所有字符串 但它没有奏效。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

要获取<actors><actors>之间的所有字符串,请使用string.gmatch进行全局匹配:

for name in string.gmatch(fixstr, "<actors>(.-)<actors>") do
    print(name)
end

请注意使用.- -匹配零次或多次,但它不贪婪。

输出:

Hrithik Roshan,
Priyanka Chopra,

实际上,除非您需要fixstr用于其他用途,否则您无需将name:character:替换为<actors>,只需一次{{1}能完成这项工作:

string.gmatch