Search code examples
lualua-patterns

Pattern matching with minus sign between spaces


I have a variable message which I get from User input. For example:

!word number word-word---word

or

!word wordword-word

Currently I create a table and fill it with every single word/number (without digits like -)

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

First of all I cant get words with minus between them to my table. Also I cant check if it[2].input is not empty. This is an example how I check the table:

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

I've tried this without any working result.


Solution

  • -- %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