我需要从一个字符中分割字符串。

我的字符串是

text1,text2

我想使用“,”来分割 text1 和 text2。

点赞
用户477878
用户477878

要获得一个包含所有子串的迭代器,可以调用string.gmatch

for i in string.gmatch(example, "%P+") do
  print(i)
end

要仅仅获得两个独立的字符串,只需调用迭代器;

> iter = string.gmatch(indata, "%P+")
> str1 = iter()
> str2 = iter()
> print (str1)
test1
> print (str2)
test2

如果您希望将它们存储在一个数组中,可以在这里找到整个讨论

@lhf在评论中添加了更好的模式“[^,]+”,我的模式则在任何标点符号处拆分,他的只在逗号处拆分。

2013-05-24 15:23:28
用户107090
用户107090

试试这个:

s="text1,text2"
t1,t2=s:match("(.-),(.-)$")
print(t1,t2)

输出结果应该是:

text1    text2
2013-05-24 15:29:49
用户1333566
用户1333566

尝试使用此页面中提供的函数:

http://lua-users.org/wiki/SplitJoin

2013-05-24 16:09:10