function repl(v) res, _ = string.gsub(v:gsub('|[()]$', ''), '|[()]', ' \\') return res end print(repl('abcdef')) print(repl('abcd|(')) print(repl('abcde|(foo')) print(repl('abcd|)')) print(repl('abcde|)foo')) --if there is no | then do nothing --if nothing follows of the |( or |) then delete these two characters --if something follows then replace |( or |) with \