Andrew V
Andrew V

Reputation: 522

How to take out only 1 word from a string in Lua

I know how to split the whole string and put it in a table but I need to take out only the first word and then the rest of the string needs to stay the same.

I tried to do something on this but I have no idea:

words = {}
for word in s:gmatch("%w+") do table.insert(words,word) end

Upvotes: 2

Views: 5668

Answers (3)

Chris P
Chris P

Reputation: 1

Ollie's solution seemed a bit overkill.

If you want to handle situations where the string may contain 1 or more words then you just need to change the 2nd capture from ".+" to ".*".

s:match("(%w+)(.*)")

Upvotes: 0

OllieBrown
OllieBrown

Reputation: 143

Yu Hao's solution has an edge case that breaks: if 's' is itself just a single word it will return that word w/o the last character to words[1] and the last character to words[2].

Here's a workaround I made that will catch this edge case properly:

local words = {}
words[1], words[2] = s:match("(%w+)(%W+)")
if words[1] == nil then words[1] = s end

Changed .+ to be \W+ (so only non-word characters can come between words). This might result in no match at all (if the string is empty or has only one word) so I check and fix that case.

There might be a better way that gets it all in a single match pattern, but I just wanted to offer this up for a workaround if anyone hits this edge case.

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122383

To match one word, you should use string.match instead of string.gmatch:

local words = {}
words[1], words[2] = s:match("(%w+)(.+)")

words[1] contains the first word, the words[2] contains the rest.

Upvotes: 5

Related Questions