Lua:替换一个子串

Lua: replace a substring

我有类似的东西

str = "What a wonderful string //011// this is"

我必须用 convertToRoman(011) 之类的东西替换 //011// 然后得到

str = "What a wonderful string XI this is"

不过这里转换成罗马数字是没有问题的。 也有可能字符串 str 没有 //...//。在这种情况下,它应该只是 return 相同的字符串。

function convertSTR(str)
  if not string.find(str,"//") then 
    return str 
  else 
    replace //...// with convertToRoman(...)
  end
  return str
end

我知道我可以使用 string.find 来获得完整的 \...\ 序列。是否有模式匹配或类似的更简单的解决方案?

string.gsub 接受一个函数作为替换。所以,这应该有效

new = str:gsub("//(.-)//", convertToRoman)

我喜欢 LPEG,因此这里有一个使用 LPEG 的解决方案:

local lpeg = require"lpeg"
local C, Ct, P, R = lpeg.C, lpeg.Ct, lpeg.P, lpeg.R

local convert = function(x)
    return "ROMAN"
end

local slashed = P"//" * (R("09")^1 / convert) * P"//"
local other = C((1 - slashed)^0)
local grammar =  Ct(other * (slashed * other)^0)

print(table.concat(grammar:match("What a wonderful string //011// this is"),""))