如何从“abcabced”中匹配“abcabc”?

我可以使用 (abc)+ 匹配 "abcabc"

但是在 Lua 中应该如何实现呢?

我的方式:

test = "abcabced"
get,getstr = "",""
while get ~= nil do
    get = string.match(test,"abc")
    getstr = getstr .. get
    test = string.gsub(test,get,"",1)
end
print(getstr)

是否有更好的方法?

原文链接 https://stackoverflow.com/questions/9668283

点赞
stackoverflow用户107090
stackoverflow用户107090

尝试一下:

s = "xabcabcabcyz"
p = ""
t = nil
repeat
    m = t
    p = p .. "abc"
    t = string.match(s, p)
until t == nil
print(m)
2012-03-12 14:31:38
stackoverflow用户1208078
stackoverflow用户1208078
str = "abcabced"
results = {}
for match in string.gmatch(str, "abc") do
    table.insert(results, match)
end

print(table.concat(results))

str = "abcabced"
results = {}
for match in string.gmatch(str, "abc") do
    table.insert(results, match)
end

print(table.concat(results))

将上面的 lua 代码翻译成中文并且保留原本的 markdown 格式:

str = "abcabced"
results = {}
for match in string.gmatch(str, "abc") do
    table.insert(results, match)
end

print(table.concat(results))

其中,string.gmatch(str, "abc") 的意思是在 str 字符串中找到所有符合 "abc" 模式的字符串,并返回一个迭代器(iterator),然后通过 for 循环来遍历这个迭代器,将每一个符合条件的字符串都加入到 results 表中。最后,通过 table.concat(results)results 表中所有的字符串都连接起来,并输出结果。

2012-03-12 17:26:48
stackoverflow用户734069
stackoverflow用户734069

如果你在讨论针对你所要求的特定情况做的事情,另外两个答案提供了合理的替代方案。但如果你在讨论_一般_情况(寻找字符串而不是字符)......那么你没有必要这样做。

Lua 的模式不是正则表达式。它们只是一个模式匹配系统。它们的功能比正则表达式要有限,但实现要小得多。如果你需要完整的正则表达式支持,可以在这里找到一个 Lua 库

2012-03-12 17:38:23