Search code examples
luapattern-matchinglua-patterns

Capture words in a tagged sentence with Lua patterns


Sample line: ('The', 'DT')('mirror', 'NN')('can', 'MD')('barely', 'RB')('contain', 'VB')('me', 'PRP')('.', '.')

What I need:

The
mirror
can
barely
contain
me
.

Using this pattern will return the whole line and not each words (plus some clatter):

txt = "('The', 'DT')('mirror', 'NN')('can', 'MD')('barely', 'RB')('contain', 'VB')('me', 'PRP')('.', '.')"

for i in txt:gmatch("%('.+',") do
    print(i)
end

Solution

  • When you use the + modifier it matches as much as it possibly can, whereas the - does the opposite. So your code is capturing a LOT, try this instead:

    for i in txt:gmatch("%('(.-)',") do
        print(i)
    end