lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


-- My version

lpeg = require "lpeg"

function spcreplace(s,this,that)
  local trans = lpeg.Cs(((lpeg.P(this) / that) + lpeg.P(1))^0)
  return trans:match(s)
end

print(spcreplace("100%% efficiency with 20%% effort","%%"," per cent"))
print(spcreplace("100% efficiency with 20% effort","%"," per cent"))
print(spcreplace("a target is here","target","%%"))
print(spcreplace("a target is here","target","%"))

-- Petite Abeille's version

function escape( s ) return ( s:gsub( '%p', '%%%1' ) ) end
function pareplace( s, this, that ) 
  return ( s:gsub( escape( this ),  escape(that)  ) )    
end  

print(pareplace("100%% efficiency with 20%% effort","%%"," per cent"))
print(pareplace("100% efficiency with 20% effort","%"," per cent"))
print(pareplace("a target is here","target","%%"))
print(pareplace("a target is here","target","%"))


Output:

100 per cent efficiency with 20 per cent effort
100 per cent efficiency with 20 per cent effort
a % is here
a 
100 per cent efficiency with 20 per cent effort
100 per cent efficiency with 20 per cent effort
a %% is here
a % is here

  -spc (Am I missing something?)