3

我有类似的东西

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

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

str = "What a wonderful string XI this is"

但是,这里转换成罗马数字是没有问题的。字符串也可能str没有//...//. 在这种情况下,它应该简单地返回相同的字符串。

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

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

4

2 回答 2

4

string.gsub接受一个函数作为替代。所以,这应该工作

new = str:gsub("//(.-)//", convertToRoman)
于 2018-11-21T11:50:46.407 回答
1

我喜欢 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"),""))
于 2018-11-22T03:10:24.697 回答