Read only last characters of a LUA string

Asked

Viewed 340 times

4

I have a string, I just want to read the last characters after the last one ";".

Example: "12/5/2015;00:00:05;90" -> Read only "90"

2 answers

3


Read 2 last characters:

str = "12/5/2015;00:00:05;90"
 print(string.sub(s, -2))

Split into 3:

str = '12/5/2015;00:00:05;90'
for word in string.gmatch(str, '([^;]+)') do
    print(word)
end

Placing each part in an Array:

 a = {} -- array 1
 b = {} -- array 2
 c = {} -- array 3

str = '12/5/2015;00:00:05;90'
op = 0
for word in string.gmatch(str, '([^;]+)') do
   op = op+1
   if op == 1 then
      a[1] = word
   elseif op == 2 then
      b[1] = word
   elseif op == 3 then
      c[1] = word
   end
end
print(a[1])
print(b[1])
print(c[1])

You can run the code and test online here

  • Thanks for your reply, but without using the string.sub Split into 3 variables, whenever there is one ";"

  • It worked @akm?

  • It worked perfectly, as I can now add each word in different arrays. Because if you do only one table.Insert() for the 3 arrays within the cycle you will always enter the same.

  • @akm, check it out now...

1

Try this:

s = "12/5/2015;00:00:05;90"
print(s:match(".*;(.+)$"))

.*; advance to the last ;.

(.+)$ captures and returns what is left, until the end of the string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.