Question

I want to parse some data from a string in Lua. I have tried several combination of string.match and string.sub but no luck. Here is the detail...

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)

Output:

Output of 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

Output of print(fixstr1)

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

What I am trying to do is get all the string between <actors>...<actors> but it didn't worked. Can anybody help on this?

Was it helpful?

Solution

To get all the strings between <actors> and <actors>, use string.gmatch for global match:

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

Note the use of .- in which - matches zero or more occurrences, but it's non-greedy.

Output:

Hrithik Roshan,
Priyanka Chopra,

Actually, unless you need fixstr for other uses, you don't need to substitute name: and character: to <actors>, just one run of string.gmatch can do the job:

for name in string.gmatch(str, "name:(.-)character:") do
    print(name)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top