string.gsub作为每个替换结果的不同变量返回

时间:2016-05-24 09:35:12

标签: string lua lua-patterns

输入:

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"}'

源代码

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

当前输出:

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

预期输出(下面的每一个都可以存储在不同的变量中)

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

1 个答案:

答案 0 :(得分:1)

你的模式中有这么多.,很难阅读,也不清楚你的目的是什么。

相反,请使用特定于格式的模式:

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

通过这种方式,每个%w+代表的内容会更加明确。

要存储结果,您使用了错误的功能。 string.gsub用于替换,请改用string.gmatch

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