Escaping strings for gsub

强颜欢笑 提交于 2019-12-04 06:25:00

According to Programming in Lua:

The character `%´ works as an escape for those magic characters. So, '%.' matches a dot; '%%' matches the character `%´ itself. You can use the escape `%´ not only for the magic characters, but also for all other non-alphanumeric characters. When in doubt, play safe and put an escape.

Doesn't this mean that you can simply put % in front of every non alphanumeric character and be fine. This would also be future proof (in the case that new special characters are introduced). Like this:

function escape_pattern(text)
    return text:gsub("([^%w])", "%%%1")
end

It worked for me on Lua 5.3.2 (only rudimentary testing was performed). Not sure if it will work with older versions.

Why not:

local quotepattern = '(['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..'])'
string.quote = function(str)
    return str:gsub(quotepattern, "%%%1")
end

to escape and then gsub it away?

try

line = '"(\.)\n(\w)", r"\1 \2"'
rx =  '\"%(%\.%)%\n%(%\w%)\", r\"%\1 %\2\"'
print(string.gsub(line, rx, ""))

escape special characters with %, and quotes with \

Try s=[["(\.)\n(\w)", r"\1 \2"]].

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!