Lua 中查找两个字符串之间的字符串

我一直在尝试查找两个字符串之间的所有可能字符串。

这是我的输入:"print/// to be able to put any amount of strings here endprint///"

目标是打印在 print///endprint/// 之间的每个字符串。

点赞
用户2858170
用户2858170

你可以使用Lua字符串模式来达成这个目的。

local text = "print/// to be able to put any amount of strings here   endprint///"

print(text:match("print///(.*)endprint///"))

模式 "print///(.*)endprint///"会捕获在 "print///""endprint///" 之间的任何字符。

2021-04-09 12:12:48
用户15459779
用户15459779

在这种问题中,你不使用贪婪量化符 *+,而是使用懒惰量化符 -。这是因为 * 匹配到后面的子模式的最后一个出现,而 - 匹配到后面的子模式的第一个出现。所以,你应该使用这个模式:

print///(.-)endprint///

要在 Lua 中匹配它,你可以这样做:

local text = "print/// to be able to put any amount of strings here   endprint///"

local match = text:match("print///(.-)endprint///")
-- `match` 现在应该是中间的文本。
print(match) -- "to be able to put any amount of strings here   "
2021-04-10 06:05:54