lua-users home
lua-l archive

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


It was thus said that the Great Thiago L. once stated:
> 
> On 21/08/14 08:33 PM, Sean Conner wrote:
> >-- 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?)
> >
> >
> I think you didn't escape `that`

  You know ... I forgot about that feature of LPeg.  Sigh.

  -spc