lua-users home
lua-l archive

Re: Odd behavior with per cent signs (forked from Re: Feature request: plain option for gsub)

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


It was thus said that the Great Sean Conner once stated:
> -- 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?)
> 
 Oops--forgot to mention---this is Lua 5.1.
 -spc (I'm not set up to test Lua 5.2)

AltStyle によって変換されたページ (->オリジナル) /