Search code examples
lualua-patterns

lua match repeating pattern


I need to encapsulate in some way pattern in lua pattern matching to find whole sequence of this pattern in string. What do I mean by that. For example we have string like that: "word1,word2,word3,,word4,word5,word6, word7," I need to match first sequence of words followed by coma (word1,word2,word3,)

In python I would use this pattern "(\w+,)+", but similar pattern in lua (like (%w+,)+), will return just nil, because brackets in lua patterns means completely different thing.

I hope now you see my problem. Is there a way to do repeating patterns in lua?


Solution

  • Your example wasn't too clear in terms of what should happen to the word4,word5,word6 and word7,

    This would give you any seqence of comma separated words without white space or empty positions.

    local text = "word1,word2,word3,,word4,word5,word6,       word7,"
    -- replace any comma followed by any white space or comma
    --- by a comma and a single white space
    text = text:gsub(",[%s,]+", ", ")
    -- then match any sequence of >=1 non-whitespace characters
    for sequence in text:gmatch("%S+,") do
      print(sequence)
    end
    

    Prints

    word1,word2,word3,
    word4,word5,word6,
    word7,