Search code examples
stringlualua-patterns

string.gsub return as a distinct variable for each replace result


Input:

stringdata = '{"abcd://ipaddress/directory1/Images/subfolder/Image0.png","abcd://ipaddress/directory1/Images/subfolder/Image1.png","abcd://ipaddress/directory1/Images/subfolder/Image2.png","abcd://ipaddress/directory1/Images/subfolder/Image3.png","abcd://ipaddress/directory1/Images/subfolder/Image4.png"}'

Source Code

string.gsub(stringdata, "(.....................%w%w................................%w)",print)

Current output:

abcd://ipaddress/directory1/Images/subfolder/Image0.png
abcd://ipaddress/directory1/Images/subfolder/Image1.png
abcd://ipaddress/directory1/Images/subfolder/Image2.png
abcd://ipaddress/directory1/Images/subfolder/Image3.png
abcd://ipaddress/directory1/Images/subfolder/Image4.png

Expected output (where each of the below could be stored in a different variable)

directory1/Images/subfolder/Image0.png    
directory1/Images/subfolder/Image1.png   
directory1/Images/subfolder/Image2.png   
directory1/Images/subfolder/Image3.png    
directory1/Images/subfolder/Image4.png

Solution

  • With so many . in your pattern, it's hard to read and unclear what's your purpose.

    Instead, use a pattern that's specific to the format:

    string.gsub(stringdata, "%w+://%w+/(%w+/%w+/%w+/%w+%.png)", print)
    

    In this way, it's much more clear what each %w+ represents.


    To store the result, you are using the wrong function. string.gsub is used for substitution, use string.gmatch instead:

    for m in string.gmatch(stringdata, "%w+://%w+/(%w+/%w+/%w+/%w+%.png)") do
      print(m)
      -- do whatever with m
    end