Lua string.gsub with a hyphen

此生再无相见时 提交于 2019-11-30 08:37:39

问题


I have two strings - each string has many lines like the following:

value_1 = "DEFAULT-VLAN"
value_2 = "WAN"
data = "HOSTNAME = DEFAULT-VLAN"
result = string.gsub(data,value_1,value_2)
print(result)

Result:

data = "HOSTNAME = DEFAULT-VLAN"

When the hyphen ("-") is deleted from the value it is working. Is there an easy way to solve this?

Thanks!


回答1:


- is a magic character in Lua patterns. You need to escape it.

Change

value_1 = "DEFAULT-VLAN"

to:

value_1 = "DEFAULT%-VLAN"



回答2:


This is because string.gsub takes a pattern similar to Regex—it does not do a "literal" replacement; this means you need to prefix any characters that have a special meaning with % to escape them.

A list of special characters that need escaping for the pattern are: (, ), ., +, -, *, ?, [, ], ^, $, and %. For the replacement string, only % has a special meaning. With this, we can write a replace function that sanitizes the inputs.

local function replace(str, what, with)
    what = string.gsub(what, "[%(%)%.%+%-%*%?%[%]%^%$%%]", "%%%1") -- escape pattern
    with = string.gsub(with, "[%%]", "%%%%") -- escape replacement
    return string.gsub(str, what, with)
end

And then you can:

result = replace(data, value_1, value_2)


来源:https://stackoverflow.com/questions/29072601/lua-string-gsub-with-a-hyphen

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