如何从用户输入的 lua 中找到特定单词(字符串)

我已经尝试了一段时间,看看用户输入的任何输入是否包含特定的单词,例如(“谢谢”,“谢谢”,“谢谢”)等

但我不确定如何找到用户输入中是否包含特定的字符串单词,我还不是很擅长 lua 编码,eep eep!

原文链接 https://stackoverflow.com/questions/70228867

点赞
stackoverflow用户2858170
stackoverflow用户2858170

Lua 参考手册来拯救!

https://www.lua.org/manual/5.4/manual.html#pdf-string.find

string.find (s, pattern [, init [, plain]]) 在字符串 s 中查找模式 (参见 §6.4.1) 的第一个匹配项。如果找到了一个匹配,find() 返回 s 中此匹配项的起始和结束索引;否则返回 nil。可选数字参数 init 指定搜索开始的位置;它的默认值为 1,可以是负数。第四个可选参数 plain 为 true 时,禁用模式匹配功能,所以该函数进行纯文本的“查找子字符串”操作,不考虑模式中的任何特殊字符。

如果模式包含捕获,则在成功匹配的情况下,两个索引之后也会返回被捕获的值。

或者

https://www.lua.org/manual/5.4/manual.html#pdf-string.match

string.match (s, pattern [, init]) 在字符串 s 中查找模式 (参见 §6.4.1) 的第一个匹配项。如果找到了一个匹配,则 match() 返回模式捕获的结果;否则返回 nil。如果模式没有指定任何捕获,则返回整个匹配项。可选数字参数 init 指定搜索开始的位置;它的默认值为 1,可以是负数。

示例:

local input = "love is in the air"
print(input:find("air"))
print(input:match("air"))

input:find("air") 基本上是 input:match("()ai()r") 的缩写。

编辑:

如果您不知道如何获取用户输入,请参阅:

https://www.lua.org/manual/5.4/manual.html#pdf-io.read

2021-12-05 08:58:37
stackoverflow用户11740758
stackoverflow用户11740758

也许这样更有帮助,因为它可以在一次运行中匹配多次并返回匹配的次数。

因此,决定 ([tT]han%g+) 模式的出现次数匹配是可能的。

用于此的魔法字符串函数是:gsub()

在 Lua 控制台中输入的示例...

> _VERSION
Lua 5.4
texts = setmetatable({}, {__call = function(self) if #self > 0 then return self[#self]:gsub('([tT]han%g+)','*%1*') end end, __index = {insert = table.insert}})
> texts:insert([[Hello ...

My name is Thomas T. Thank
I would like to thank you...
Thanks in advance]])
> texts()
Hello ...

My name is Thomas T. *Thank*
I would like to *thank* you...
*Thanks* in advance 3
> do local txt, occ = texts() if occ > 0 then io.write(occ,' occurencies in...\n', txt, '\n...found.\n') end end
3 occurencies in...
Hello ...

My name is Thomas T. *Thank*
I would like to *thank* you...
*Thanks* in advance
...found.

...同样 gsub() 是一个很好的翻译或查找替换函数。

2021-12-05 15:42:54