user2418051
user2418051

Reputation: 81

I need to split string from a character

My string is

text1,text2

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

Upvotes: 1

Views: 401

Answers (3)

cgokmen
cgokmen

Reputation: 1719

Try the functions given in this page:

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

Upvotes: 0

lhf
lhf

Reputation: 72312

Try this:

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

Upvotes: 4

Joachim Isaksson
Joachim Isaksson

Reputation: 180887

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.

Upvotes: 0

Related Questions