【问题标题】:Pattern matching with minus sign between spaces空格之间带有减号的模式匹配
【发布时间】:2015-07-19 22:46:41
【问题描述】:

我有一个变量message,我从用户输入中获得。例如:

!字数 字字---字

!字 一字一字

目前我创建了一个表格并用每个单词/数字填充它(没有像 - 这样的数字)

--input table
it = {}
--put input in table
for _input in string.gmatch((message), '%w+') do
    it[#it+1] = { input=_input }
end

首先,我无法将它们之间带有减号的单词放到我的桌子上。 我也无法检查it[2].input 是否不为空。这是我如何检查表格的示例:

--TEST START
if it[1].input == 'test' then
    --do something
end
--TEST END

我试过this 没有任何工作结果。

【问题讨论】:

  • 尝试string.gmatch(message, '%S+') 获取带有破折号的单词。尝试if (it[1] or {}).input == 'test' then 检查值。
  • 太棒了……就这么简单……非常感谢!!!
  • !word 是有效词还是 word

标签: lua lua-patterns


【解决方案1】:
-- %s = space character
-- %- = escaped magic character
message = "!word number word-word---word"
-- might not be the most ideal method to fil an array up...
it = {(function() local t = {}; for _input in string.gmatch(message,"[^%s%-]+") do t[#t+1] = {input = _input} end return unpack(t) end)()}
print(t[2].input) --> number
--
--
it = {}
for _input in string.gmatch(message,"[^%s%-]+") do
    it[#it+1] = {input = _input}
end
-- now checking value should work fine
if (it[2] and it[2].input == "number") then -- checking that it[2] is set as something and then comparing input
   print("t[2].input = \"number\"");
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多