Scott H.
Scott H.

Reputation: 143

lua pattern matching: delimited captures

I am trying to parse a string such as: &1 first &2 second &4 fourth \\, and from it to build a table

t = {1=first, 2=second, 4=fourth}

I'm not very experienced with regex in general so my naive try (disregarding the \\ and table parts for the moment) was

local s = [[&1 first &2 second &4 fourth \\]]

for k,v in string.gmatch(s, "&(%d+)(.-)&") do
    print("k = "..k..", v = "..v)
end

which gives only the first captured pair when I was expecting to see two captured pairs. I've done some reading and found the lpeg library, but it's massively unfamiliar to me. Is lpeg needed here? Could anyone explain my error?

Upvotes: 4

Views: 151

Answers (2)

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

If you know that the values are one word, this should work:

string.gmatch(s, "&(%d+)%s+([^%s&]+)")

Take "&", followed by 1 or more digits (captured), followed by one or more space and then one or more non-space, non-& characters (captured).

Upvotes: 1

Eric
Eric

Reputation: 97691

  1. &(%d+)(.-)& matches &1 first &
  2. Leaving 2 second &4 fourth \\ to be matched on
  3. Your pattern does not match any further items

Upvotes: 2

Related Questions