匹配字符集中的几个符号

问题描述

Lua(以及我认为的任何其他正则表达式)具有允许匹配集合中任何符号的字符集。有没有办法将集合中的多个符号匹配为一个?示例

text:gsub("foo[^bar]-","") -- matches for any foo that is not followed by 'b','a' or 'r'

有没有办法让它允许 'b'、'a' 或 'r',但不允许后面完全是 'bar'(也许还有几个非一个符号)模式?

解决方法

local s = "{aaa\\rbbb} {ccc\\r\\alpha} {eee\\r}"
print(s)

local s1 = s:gsub("(\\r[^}]-)}","%1\\alpha&H&}")
print(s1)

local s2 = s:gsub("\\alpha","\0%0")  -- insert zero byte before each \alpha
            :gsub("(\\r%f[^r%z][^}]*)}","%1\\alpha&H&}")
            :gsub("%z","")           -- remove all zero bytes
print(s2)

输出:

{aaa\rbbb} {ccc\r\alpha} {eee\r}
{aaa\rbbb\alpha&H&} {ccc\r\alpha\alpha&H&} {eee\r\alpha&H&}
{aaa\rbbb\alpha&H&} {ccc\r\alpha} {eee\r\alpha&H&}