简体   繁体   中英

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

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.

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.

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+)(.*)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM