Lua字符串的利刃:模式匹配的艺术与实践

一、字符串的不可变性与核心函数库

  1. 字符串是不可变的:你不能像在某些语言中那样直接修改字符串的某个字符。所有字符串函数都不会改变原始字符串,而是返回一个新的、修改后的字符串。
  2. 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 的子字符串捕获,用于 matchgsub
  • % : 转义字符。用于匹配魔法字符本身,例如 %. 匹配一个真正的点,%% 匹配一个百分号。

重复匹配修饰符 (Modifiers):

  • *: 匹配前一个字符或类别 0 次或多次(贪婪模式,匹配尽可能长的)。
  • +: 匹配 1 次或多次(贪婪模式)。
  • ?: 匹配 0 次或 1 次。
  • - : 匹配 0 次或多次(非贪婪模式 ,匹配尽可能短的)。这是 * 的一个非常有用的变体。

边界匹配:

  • ^: 匹配字符串的开头。
  • $: 匹配字符串的结尾。

结语

点个赞,关注我获取更多实用 Lua 技术干货!如果觉得有用,记得收藏本文!

相关推荐
崔庆才丨静觅2 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60613 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了3 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅3 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅4 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅4 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment4 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅5 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊5 小时前
jwt介绍
前端
爱敲代码的小鱼5 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax