You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua正则匹配问题:匹配字符至指定字符或字符串末尾

解决Lua正则匹配到指定字符或字符串末尾的问题

问题出在原正则使用的**正向预查(?[-])**要求后面必须存在目标字符,没有时匹配直接失败。要实现「匹配到指定字符,无则到末尾」的需求,只需调整正则逻辑:

修正后的正则写法

1. 匹配+开头到-(或末尾)的内容

把原正则:

string.match(id, "^[+](.+)(?[-])")

替换为:

string.match(id, "^[+]([^-]*)")
  • [^-]*:匹配任意**非-**的字符,直到遇到-或字符串结尾,完美覆盖两种场景。

2. 匹配-开头到+(或末尾)的内容

把原正则:

string.match(id, "^[-](.+)(?[+])")

替换为:

string.match(id, "^[-]([^+]*)")
  • [^+]*:同理,匹配任意非+的字符,直到遇到+或结尾。

测试验证

场景1:存在结束字符

local id = "+@a-@s,@n"
local addOperator = string.match(id, "^[+]([^-]*)") -- 返回 "@a"

local id2 = "-@s,@n+xxx"
local removeOperator = string.match(id2, "^[-]([^+]*)") -- 返回 "@s,@n"

场景2:无结束字符

local id = "+@a"
local addOperator = string.match(id, "^[+]([^-]*)") -- 返回 "@a"

补充说明

如果需要匹配到最后一个指定字符(而非第一个),可以改用贪婪匹配结合可选的结束符:

-- 匹配+开头到最后一个-(或末尾)的内容
string.match(id, "^[+](.*)(?:-|$)")

但通常需求是匹配到第一个分隔符,所以[^-]*的写法更高效且符合常规场景。

内容的提问来源于stack exchange,提问作者szkiddaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:55:25