string 모듈의 find 또는 gmatch 함수를 이용한다.
find 함수는 정규식과 일치하는 부분의 시작과 끝 인덱스를 반환한다. 정규식이 그룹화된 것이라면, 시작과 끝 인덱스 외에도 해당 문자열도 반환한다.
string.find (s, pattern [, init [, plain]])
local b1, e1, pattern = string.find("abcd12efgh", "[a-z]+") print(b1, e1, pattern) local b1, e1, pattern = string.find("abcd12efgh", "([a-z]+)") print(b1, e1, pattern)
1 4 nil 1 4 abcd
gmatch 함수는 iterator 함수를 반환한다. 이 함수는 호출할 때마다 다음으로 일치하는 문자열을 반환한다.
string.gmatch (s, pattern)
s = "hello world from Lua" for w in string.gmatch(s, "%a+") do print(w) end
hello world from Lua
string 모듈의 gsub 함수를 이용한다.
string.gsub (s, pattern, repl [, n])
print(string.gsub("hello world", "(%w+)", "%1 %1")) print(string.gsub("hello world", "%w+", "%0 %0", 1)) print(string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1"))
hello hello world world 2 hello hello world 1 world hello Lua from 2
특이한 것은 치환할 대상(repl)으로 문자열 뿐만 아니라, 테이블, 함수 등을 전달할 수도 있다는 점인데, 이에 관한 것은 루아 매뉴얼을 참고하길 바란다.