Search code examples
luagsublua-patterns

Match for several symbols in char-set


Lua's (and any other regex I think) have char-sets that allow matching for any symbol in the set. Is there a way to match several symbols from that set as one? Example

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

Is there a way to make it allow 'b', 'a' or 'r', but not allow exactly 'bar' (and maybe a few more non-one symbol) patterns after?


Solution

  • 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)
    

    Output:

    {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&}