[英]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.我知道如何拆分整个字符串并将其放入表中,但我只需要取出第一个单词,然后字符串的 rest 需要保持不变。
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
:要匹配一个单词,您应该使用string.match
而不是string.gmatch
:
local words = {}
words[1], words[2] = s:match("(%w+)(.+)")
words[1]
contains the first word, the words[2]
contains the rest. words[1]
包含第一个单词, words[2]
包含其余words[2]
。
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]. Yu Hao 的解决方案有一个突破性的边缘情况:如果 's' 本身只是一个单词,它将返回该单词,而不是将最后一个字符返回到 words[1],将最后一个字符返回到 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).将.+
更改为\\W+
(因此单词之间只能出现非单词字符)。 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 ".*".如果你想处理字符串可能包含 1 个或多个单词的情况,那么你只需要将第二次捕获从“.+”更改为“.*”。
s:match("(%w+)(.*)")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.