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

Luaの文字列の位置を取得するサンプルです。

目次

01. 文字列の位置を取得する

前から検索する

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

前から検索する

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)  -- エラー

日本語の場合

日本語の場合は、以下のようになります。

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)  -- エラー

日本語の場合

日本語の場合は、以下のようになります。

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)  -- エラー

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

関連の記事

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

△上に戻る