如何循环遍历字符串中的每一个 string.gmatch 并用该字符串的字节码版本替换匹配项?

如何在不更改非匹配项的情况下将字符串中所有匹配项替换为其他内容?

local a = "\" Hello World! I want to replace this with a bytecoded version of this!\" but not this!"

for i in string.gmatch(a, "\".*\"") do
    print(i)
end

例如,我想将 [["Hello World!" Don't Replace this!]] 替换为 [["\72\101\108\108\111\32\87\111\114\108\100\33" Don't Replace this!]]

原文链接 https://stackoverflow.com/questions/70119175

点赞
stackoverflow用户8294610
stackoverflow用户8294610

你需要使用 string.gsub

local a = "\"Hello World!\" Don't Replace this!"
local function convert(str)
  local byte_str = ""
  for i = 1, #str do
    byte_str = byte_str .. "\\" .. tostring(string.byte(str, i))
  end
  return byte_str
end
a = string.gsub(a, "\"(.*)\"", function(matched_str)
  return "\"" .. convert(matched_str) .. "\""
end)
print(a)
2021-11-26 03:24:54
stackoverflow用户4984564
stackoverflow用户4984564
local a = "\"Hello World!\" but not this!"

print(a:gsub('"[^"]*"', function(str)
  return str:gsub('[^"]', function(char)
    return "\\" .. char:byte()
  end)
end))

本地定义了一个字符串变量 a,其中包含一个双引号为边界的子字符串 "Hello World!"。然后使用 Lua 字符串中的 gsub 函数,对于所有双引号为边界的子字符串执行一个匿名函数。在匿名函数中,对于字符串中的每个字符,如果不是双引号,则将其转换为对应的 ASCII 码并在前面加上反斜杠转义符。最终输出结果为 "\"72\97\108\108\111\32\87\111\114\108\100\33\" but not this!"

2021-11-26 10:29:28
stackoverflow用户2858170
stackoverflow用户2858170
local a = "\" Hello World! I want to replace this with a bytecoded version of this!\" but not this!"

print((a:gsub('%b""' , function (match)
  local ret = ""
  for _,v in ipairs{match:byte(1, -1)} do
    ret = ret .. string.format("\\%d", v)
  end
  return ret
end)))

将字符串变量 a 中的双引号中的字符转为其ASCII码的转义字符格式,并保留双引号之外的字符不变。输出结果为转义后的字符串。

2021-11-26 11:45:33