luapattern-matchinglua-patterns

Lua pattern matching problem with escaped letter


I've already had a rule that \ should be replaced with \\\\ , so the existed code is

string.gsub(s, '\\', '\\\\\\\\')

but there is some data that should not be converted, such as abc\"cba, which will be replaced with abc\\\\"cba.

How can I constraint that only \ followed without " can be replaced, such like


'abc\abc' -> 'abc\\\\abc'

'abc\"abc' -> 'abc\"abc'

I have used patterns like \\[^\"]- and \\[^\"]+- but none of them works.

Thanks


Solution

  • You can use

    string.gsub((s .. ' '), '\\([^"])', '\\\\\\\\%1'):sub(1, -2)
    

    See the online demo:

    local s = [[abc\abc abc\"abc\]];
    s = string.gsub((s .. ' '), '\\([^"])', '\\\\\\\\%1'):sub(1, -2)
    print( s );
    -- abc\\\\abc abc\"abc\\\\
    

    Notes: