12

I have a string in lua.

It's a bunch of [a-zA-Z0-9]+ separated by a number (1 or more) spaces.

How do I take the string and split it into a table of strings?

1

3 Answers 3

47
s="How do I take the string and split it into a table of strings?"
for w in s:gmatch("%S+") do print(w) end
3
  • 10
    reference manual gnome says: %S represents all non-space characters. Commented May 6, 2010 at 15:45
  • 10
    The accepted answer (ponzao) is ok with the specification in the question, but the reason to prefer lhf's answer is that if you have 8-bit or multibyte text (everything non-ascii), you can still split correctly on only spaces using this method. Commented May 6, 2010 at 15:50
  • @u0b34a0f6ae So, for example, it would work with UTF-8 encoding. : ]]] (but not with some Unicode special whitespaces that use longer code points)
    – user5066707
    Commented Mar 22, 2017 at 10:53
20
s = "foo bar 123"
words = {}
for word in s:gmatch("%w+") do table.insert(words, word) end
3
  • 6
    reference manual gnome says: %w represents all alphanumeric characters. Commented May 6, 2010 at 15:44
  • %w not correct for me, it includes an alphanumeric character for spliting. e.g "FAULT_CODE FAULTCODE" return 3 values Commented Jan 28, 2019 at 14:08
  • 2
    @PankajRawat, well the original question specified [a-zA-Z0-9]+ which would not include _. You'd probably want to use the answer provided by @lhf.
    – ponzao
    Commented Jan 31, 2019 at 22:03
0

Here is an example how to split words and merge them:

function mergeStr (strA, strB)
  local tablA, tablB = {}, {}
  for word in strA:gmatch("%S+") do
    table.insert (tablA, word)
  end
  for word in strB:gmatch("%S+") do
    table.insert (tablB, word)
  end
  return tablA[1] .. ' ' .. tablB[3] .. ' ' .. tablA[5]
end

print (mergeStr ("Lua is a programming language", "I love coding"))
-- "Lua coding language"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.