如何在字符串中进行模式匹配?

有没有一种方法可以迭代逗号分隔的字符串,然后对匹配项执行某些操作?到目前为止我有:

for a in string.gmatch("this, is, a commaseparated, string", "(.-)[,]") do
  print (a)
end

问题是表中的最后一个条目找不到。在 C 中,可以匹配 NULL 来检查是否处于字符串的末尾。Lua 中有类似的东西吗?

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

点赞
stackoverflow用户88888888
stackoverflow用户88888888

尝试一下:

for a in string.gmatch("this, is, a commaseparated, string", "([^,]+),?") do
    print (a)
end

正则表达式模式 ([^,]+),? 捕获一个或多个非逗号字符,后面可选跟随一个逗号。

2011-03-24 05:43:03