lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


And as a follow-up on the lpeg hint, here's my toss at it:

space = lpeg.S " \t"
sp = space^0
eq = lpeg.P "="
name = lpeg.C((1 - (space + eq))^1, "name")
sval = lpeg.C((1 - space)^1, "value")
q = lpeg.P "'"
qq = lpeg.P '"'
qval = q* lpeg.C((1 - q)^0, "value")* q
qqval = qq* lpeg.C((1 - qq)^0, "value")* qq
pair = lpeg.T(sp* name* sp* eq* sp* (qval + qqval + sval))
args = lpeg.T(pair^0)

function extract_args(s)
	m = lpeg.match(s, args)
	if m then
		print("Matches:", m)
		for k, v in pairs(m) do
			print(k, v)
			if type(v) == "table" then
				for n, s in pairs(v) do
					print("", n, s)
				end
			end
		end
	else
		print("No match")
	end
end

extract_args[[class=q href="http://images.goo gle.se/imghp?hl=sv&tab=wi" onClick='return qs(this);' test=foo]]

Matches:        table: 0x552050
1       table: 0x5520a0
        name    class
        value   q
2       table: 0x5521a0
        name    href
        value   http://images.goo gle.se/imghp?hl=sv&tab=wi
3       table: 0x552250
        name    onClick
        value   return qs(this);
4       table: 0x552380
        name    test
        value   foo

It's alot more verbose, but I like the power that comes with it :)

Andreas Stenius skrev:
Luiz Henrique de Figueiredo skrev:
No, not alternates like that, simply to be able to:

foo:gsub("(.-)[%s$]", bar)

Then try foo:gsub("(.-)%s?$", bar).

Yes, but this will make the capture greedy.. what saved me was that when I read the source in lstrlib.c I found the frontiers: %f[...] which saved me by simply appending a space at the end of my subject.

What made this more problematic was that I wanted to match

[[name=value name2='other val' name3="no, should I match this as well!"]]

where the value MIGHT be enclosed in single OR double quotes, and with quotes, there may be spaces between the quotes too ;o).

So my pattern I successfully use now isn't pretty:

-- snippet is part of a bigger function

    local function parseargs()
        local t = {}
        ;(args .. " "):gsub("(%w+)%s*=%s*([\"']?)(.-)%2%f[%s]",
            function( k, _, v )
                t[k:lower()] = v
                return ""
            end)
        return t
    end



--
Med vänlig hälsning,
Andreas Stenius
_________________________________
Boxcom AB

E-post: andreas@boxcom.se
Tel: 08-550 330 50
Fax: 08-550 330 52
Mobil: 070-442 22 50
Web: www.boxcom.se

Virkesvägen 10, 152 42 Södertälje

Automatiska körjournaler - IT-Tjänster
Med en dosa i bilen får du koll på milen!

begin:vcard
fn:Andreas Stenius
n:Stenius;Andreas
org:Boxcom AB
adr;quoted-printable;quoted-printable:;;Virkesv=C3=A4gen 10;S=C3=B6dert=C3=A4lje;;15242;Sweden
email;internet:andreas@boxcom.se
tel;work:08-550 330 50
tel;fax:08-550 330 52
tel;cell:070-44 22 250
url:http://www.boxcom.se
version:2.1
end:vcard