First of all this doesn't match ok or capture
"ok".find("(ok|capture)") -- nil
Second, followed by ok
match an optional ok;args
but only capture args
as parameter. This is wrong "ok;args".find("(ok)(;.+)?")
, and capture group includes extra ;
.
function mymatch(str)
local _, _, ok, oreveal = str:find("(ok)")
return ok, oreveal
end
-- this is what I want
print(mymatch("ok")) -- ok nil
print(mymatch("cancel")) -- cancel nil
print(mymatch("ok;domatch")) -- ok domatch
print(mymatch("okdontmatch")) -- nil nil
You can use
function mymatch(str)
local _, _, ok, oreveal = str:find("^(ok%f[%A]);?(.*)$")
if ok == nil then
_, _, ok, oreveal = str:find("^(cancel%f[%A]);?(.*)$")
end
if oreveal == "" then
oreveal = nil
end
return ok, oreveal
end
-- this is what I get
print(mymatch("ok")) -- ok nil
print(mymatch("cancel")) -- cancel nil
print(mymatch("ok;domatch")) -- ok domatch
print(mymatch("okdontmatch")) -- nil nil
See the online Lua demo.
The ^(ok%f[%A]);?(.*)$
pattern matches
^
- start of string(ok%f[%A])
- Group 1: ok
and a trailing "word boundary" (%f[%A]
is a frontier pattern making sure that the next char if present must be a non-letter);?
- an optional ;
(.*)
- Group 2: the rest of the string$
- end of string.