s = [[then he said: "it's all right"!]]
q, quotePart = s:match("([\"'])(.-)%1") --> 通常の正規表現でいうところの\1
print(quotePart) --> it's all right
print(quote) --> "
s = "hello world"
i, j = string.find(s, "hello")
print(i, j) ---> 1, 5
s.sub(1,5) ---> "hello"
a, b = string.find("ABCDE", "BC") -- a=2, b=3
a, b = string.find("ABCDE", "%a*") -- a=1, b=5
a, b = string.find("ABCDE", /\a*/) -- a=1, b=5
a, b = string.find("あいうえお", "いう") -- a=3, b=6
a, b, c = string.find("ABCDE", "B(.)D") -- a=2, b=4, c="C"
x, y = string.gsub("HELLO world", /o/i, "o")
-- x = "HELLo world", y = 2
x, y = string.gsub("hello world", "(%w+)", "%1 %1")
-- x = "hello hello world world", y = 2
x, y = string.gsub("hello world from Lua", /(\w+)\s*(\w+)/, "%2 %1")
-- x = "world hello Lua from", y = 2
t = { name = "lua", version = "5.1" }
x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
-- x = "lua-5.1.tar.gz"
function f(s)
if s == "hello" then
return "bye"
elseif s == "world" then
return "universe"
else
return "unknown"
end
end
x = string.gsub("hello world", "(%w+)", f) -- x = "bye universe"
テーブル
function expands (s)
return (s:gsub("$(%w+)", _G)) --> 該当のキャプチャを、テーブルのキーとして評価して、_G[key]を返す。( ) を付けることで、1番目のみ返す。
end
name = "Lua"; status = "great"
print(expands("$name is $status, isn't it?")) --> Lua is great, isn't it?
関数
function expands (s)
return (s:gsub("$(%w+)", function (n) return tostring(_G[n]) end))
end
print(expands("print=$print"; a = $a))
--> print = function: 0x8f9das0f0; a = nil