【问题标题】:Lua: replace a substringLua:替换子字符串
【发布时间】:2019-04-23 23:24:50
【问题描述】:

我有类似的东西

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 来获得完整的\\...\\ 序列。有没有更简单的模式匹配或类似的解决方案?

【问题讨论】:

    标签: lua substring lua-patterns


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我喜欢 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"),""))
      

      【讨论】:

        猜你喜欢
        • 2011-05-16
        • 2019-03-08
        • 2012-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-15
        • 1970-01-01
        • 2014-08-06
        相关资源
        最近更新 更多