Search code examples
lualove2d

I need to split string from a character


My string is

text1,text2

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


Solution

  • 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.