Question

My string is

text1,text2

I want to split text1 and text2 by using the ','.

Was it helpful?

Solution 2

To get an iterator with the substrings, you can call string.gmatch.

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

To just get them into two separate strings, you can just call the iterator;

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

If you want them stored in an array instead, there's a whole discussion here how to achieve that.

@lhf added a better pattern [^,]+ in the comments, mine splits on any punctuation, his only on comma.

OTHER TIPS

Try this:

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

Try the functions given in this page:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top