2

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?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks it worked like charm. But becouse its in loop it will give output in new line every time it runs i want it in single string like .....Hrithik Roshan,Priyanka Chopra,Sanjay Dutt,Rishi Kapoor,Zarina Wahab,Om Puri,
@user1640175 The new line is added by print. You can initialize an empty string result = "" and concatenate the names to it in the loop result = result .. name.
@user1640175, you can also use io.write(name,' ') instead of print.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.