3

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Red-Cloud
  • 438
  • 6
  • 13

2 Answers2

4

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

new = str:gsub("//(.-)//", convertToRoman)
lhf
  • 70,581
  • 9
  • 108
  • 149
1

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"),""))
Henri Menke
  • 10,705
  • 1
  • 24
  • 42