一、字符串的不可变性与核心函数库
- 字符串是不可变的:你不能像在某些语言中那样直接修改字符串的某个字符。所有字符串函数都不会改变原始字符串,而是返回一个新的、修改后的字符串。
string库 :所有字符串操作都通过全局的string表来完成。
二、模式匹配的四个核心函数
1. string.find(s, pattern) -- 查找
它在一个字符串中搜索一个模式,如果找到,返回匹配部分的起始和结束索引 ;否则返回 nil。
lua
local s = "hello world"
local start_idx, end_idx = string.find(s, "world")
print(start_idx, end_idx) -- 输出: 7 11
local found = string.find(s, "goodbye")
print(found) -- 输出: nil
2. string.match(s, pattern) -- 提取
它与 find 类似,返回匹配到的那部分字符串 。如果模式中包含捕获(captures),它会返回捕获到的内容。
lua
local s = "My name is David."
print(string.match(s, "David")) -- 输出: David
-- 使用捕获 () 来提取数字
local text = "Version: 1.2.3"
local version_num = string.match(text, "Version: (%d%.%d%.%d)")
print(version_num) -- 输出: 1.2.3
3. string.gmatch(iterator_s, pattern) -- 迭代
它返回一个迭代器函数,让你可以用 for 循环遍历一个字符串中所有匹配模式的地方。
lua
local s = "apple,banana,orange"
-- 提取所有非逗号的单词
for word in string.gmatch(s, "([^,]+)") do
print(word)
end
-- 输出:
-- apple
-- banana
-- orange
4. string.gsub(s, pattern, replacement) -- 替换
在一个字符串中查找所有匹配模式的地方,并用指定内容进行替换。
lua
local s = "hello world"
-- 简单替换
local s2 = string.gsub(s, "world", "Lua")
print(s2) -- 输出: hello Lua
-- 进阶:使用捕获进行替换
local date = "2025-10-29"
local formatted_date = string.gsub(date, "(%d+)-(%d+)-(%d+)", "%3/%2/%1")
print(formatted_date) -- 输出: 29/10/2025
-- 终极:使用函数进行替换
local text = "I have 3 apples and 5 oranges."
local new_text = string.gsub(text, "(%d+)", function(n)
return n * 2 -- 将所有数字翻倍
end)
print(new_text) -- 输出: I have 6.0 apples and 10.0 oranges.
三、模式语法速查手册
Lua 的模式由普通字符和一些具有特殊含义的"魔法字符"组成。
.: 匹配任意单个字符。%a: 匹配任意字母。%d: 匹配任意数字。%s: 匹配任意空白字符(空格、制表符、换行等)。%w: 匹配任意字母和数字。%l/%u: 匹配任意小写 / 大写字母。- 大写字母 (
%A,%D,%S,%W): 匹配对应小写版本的补集 (例如%D匹配任何非数字字符)。 [set]: 匹配集合set中的任意字符(例如[abc])。[^set]: 匹配任意不在 集合set中的字符。(pattern): 捕获 。将匹配pattern的子字符串捕获,用于match或gsub。%: 转义字符。用于匹配魔法字符本身,例如%.匹配一个真正的点,%%匹配一个百分号。
重复匹配修饰符 (Modifiers):
*: 匹配前一个字符或类别 0 次或多次(贪婪模式,匹配尽可能长的)。+: 匹配 1 次或多次(贪婪模式)。?: 匹配 0 次或 1 次。-: 匹配 0 次或多次(非贪婪模式 ,匹配尽可能短的)。这是*的一个非常有用的变体。
边界匹配:
^: 匹配字符串的开头。$: 匹配字符串的结尾。
结语
点个赞,关注我获取更多实用 Lua 技术干货!如果觉得有用,记得收藏本文!