gpt4 book ai didi

lua - 转义 gsub 的字符串

转载 作者:行者123 更新时间:2023-12-04 13:17:15 28 4
gpt4 key购买 nike

我读了一个文件:

local logfile = io.open("log.txt", "r")
data = logfile:read("*a")
print(data)

输出:
...
"(\.)\n(\w)", r"\1 \2"
"\n[^\t]", "", x, re.S
...

是的,日志文件看起来很糟糕,因为它充满了各种命令

怎么打电话 gsub并删除即 "(\.)\n(\w)", r"\1 \2"来自数据变量的行?

下面的片段,不起作用:
s='"(\.)\n(\w)", r"\1 \2"'
data=data:gsub(s, '')

我想需要做一些转义。有什么简单的解决办法吗?

更新 :
local data = [["(\.)\n(\w)", r"\1 \2"
"\n[^\t]", "", x, re.S]]

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

local function esc(x)
return (x:gsub('%%', '%%%%')
:gsub('^%^', '%%^')
:gsub('%$$', '%%$')
:gsub('%(', '%%(')
:gsub('%)', '%%)')
:gsub('%.', '%%.')
:gsub('%[', '%%[')
:gsub('%]', '%%]')
:gsub('%*', '%%*')
:gsub('%+', '%%+')
:gsub('%-', '%%-')
:gsub('%?', '%%?'))
end

print(data:gsub(esc(s), ''))

这似乎工作正常,只是我需要转义,转义字符 % , 因为如果 % 它将不起作用在匹配的字符串中。我试过 :gsub('%%', '%%%%'):gsub('\%', '\%\%')但它不起作用。

更新 2 :

好的, %如果首先在我刚刚更正的“表格”上方设置,则可以通过这种方式进行转义

:可怕的经历:

更新 3 :
^的转义和 $
如 Lua 手册所述( 5.15.25.3 )

A caret ^ at the beginning of a pattern anchors the match at the beginning of the subject string. A $ at the end of a pattern anchors the match at the end of the subject string. At other positions, ^ and $ have no special meaning and represent themselves.



所以更好的主意是逃避 ^$仅当它们被找到(分别)和字符串的开头或结尾时。

Lua 5.1 - 5.2+ 不兼容

string.gsub now raises an error if the replacement string contains a % followed by a character other than the permitted % or digit.



没必要每 %加倍在替换字符串中。见 lua-users .

最佳答案

根据 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.

这是否意味着您可以简单地输入 %在每个非字母数字字符前面,没问题。这也将是 future 的证明(在引入新的特殊字符的情况下)。像这样:

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

它在 Lua 5.3.2 上对我有用(只进行了基本测试)。不确定它是否适用于旧版本。

关于lua - 转义 gsub 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9790688/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com