Lua 文字列の位置を取得(string.find)

目次

前から検索する

string.find(文字列, 検索する文字列)

string.findは、前から検索し最初の一致の開始・終了位置を返します。

local str1 = "abcabc"

local start_pos, end_pos = string.find(str1, "a")
print(start_pos, end_pos) -- 1 1

local start_pos, end_pos = string.find(str1, "b")
print(start_pos, end_pos) -- 2 2

local start_pos, end_pos = string.find(str1, "c")
print(start_pos, end_pos) -- 3 3

local start_pos, end_pos = string.find(str1, "abc")
print(start_pos, end_pos) -- 1 3

local start_pos, end_pos = string.find(str1, "Z")
print(start_pos, end_pos) -- nil nil

日本語の場合

日本語の場合は、以下のようになります。(utf-8のとき)

local str2 = "あいうあいう"
local start_pos, end_pos = string.find(str2, "あ")
print(start_pos, end_pos) -- 1 3

local start_pos, end_pos = string.find(str2, "い")
print(start_pos, end_pos) -- 4 6

local start_pos, end_pos = string.find(str2, "う")
print(start_pos, end_pos) -- 7 9

UTF-8のため3バイトになっています。

前から検索する+開始位置を指定

string.find(文字列, 検索する文字列,検索を始める位置)

3つめの引数に開始位置を指定します。

local str1 = "abcabc"

local start_pos, end_pos = string.find(str1, "a", 1)
print(start_pos, end_pos) -- 1 1

local start_pos, end_pos = string.find(str1, "b", 2)
print(start_pos, end_pos) -- 2 2

local start_pos, end_pos = string.find(str1, "c", 3)
print(start_pos, end_pos) -- 3 3

local start_pos, end_pos = string.find(str1, "a", 4)
print(start_pos, end_pos) -- 4 4

local start_pos, end_pos = string.find(str1, "a", 5)
print(start_pos, end_pos) -- nil nil

日本語の場合

日本語の場合は、以下のようになります。(utf-8のとき)

local str2 = "あいうあいう"
local start_pos, end_pos = string.find(str2, "あ", 1)
print(start_pos, end_pos) -- 1 3

local start_pos, end_pos = string.find(str2, "あ", 4)
print(start_pos, end_pos) -- 10 12

local start_pos, end_pos = string.find(str2, "あ", 7)
print(start_pos, end_pos) -- 10 12

local start_pos, end_pos = string.find(str2, "あ", 10)
print(start_pos, end_pos) -- 10 12

local start_pos, end_pos = string.find(str2, "あ", 11)
print(start_pos, end_pos) -- nil nil

UTF-8のため3バイトになっています。

パターン検索

local text = "abc123xyz"

local start_pos, end_pos = string.find(text, "%d+")
print(start_pos, end_pos) -- 4 6

%d+は数字が1回以上続くを意味します= 123。

完全一致(パターンを無効化)

パターンを使わずそのまま文字列で検索したい場合です。

local text = "a.b.c"

local start_pos, end_pos = string.find(text, ".", 1, true)
print(start_pos, end_pos) -- 2 2

第4引数にtrueをつけるとパターン無効になります(.をそのまま検索))。

関連の記事

Lua 文字列を結合するサンプル

△上に戻る