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?

0

2 Answers 2

4

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

new = str:gsub("//(.-)//", convertToRoman)
Sign up to request clarification or add additional context in comments.

Comments

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"),""))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.