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:

    • \\([^"]) - matches two chars, a \ and then any one char other than a " char (that is captured into Group 1)
    • \\\\\\\\%1 - replacement pattern that replaces each match with 4 backslashes and the value captured in Group 1
    • (s .. ' ') - a space is appended at the end of the input string so that the pattern could consume a char other than a " char
    • :sub(1, -2) - removes the last "technical" space that was added.