Red-Cloud
Red-Cloud

Reputation: 458

Lua: replace a substring

I have something like

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

I have to replace the //011// with something like convertToRoman(011) and then get

str = "What a wonderful string XI this is"

However, the conversion into roman numbers is no problem here. It is also possible that the string str didn't has a //...//. In this case it should simply return the same string.

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

I know that I can use string.find to get the complete \\...\\ sequence. Is there an easier solution with pattern matching or something similiar?

Upvotes: 3

Views: 761

Answers (2)

Henri Menke
Henri Menke

Reputation: 10939

I like LPEG, therefore here is a solution with 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"),""))

Upvotes: 1

lhf
lhf

Reputation: 72312

string.gsub accepts a function as a replacement. So, this should work

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

Upvotes: 4

Related Questions