lua-users home
lua-l archive

Re: Feature request: plain option for gsub

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


2014年08月21日 16:54 GMT+02:00 Jonas Thiem <jonasthiem@googlemail.com>:
> I wrote up this lengthy function which is supposed to behave like
> a gsub with plain=True
That "lengthy" is a challenge ... here is my attempt, which has the
same fourth parameter that gsub has. 'gfind' is an independently
useful iterator form of find, except that the default is plain: you need
to specify "false" as second argument to get a pattern.
string.gfind = function (str,plain)
-- for j,i in str:gfind(plain),s do iterates through pairs i,j that would
-- be returned by s:find(str,init,plain) for suitably chosen init
 return function(a,idx)
 local i,j = a:find(str,(idx or 0)+1,plain)
 return j,i
 end
end
string.rawgsub = function(s, pattern, repl, n)
-- like gsub, except matching is plain
 n = n or 0
 local buffer={}
 local oldk=1
 for j,i in pattern:gfind(true),s do
 if i>oldk then buffer[#buffer+1]=s:sub(oldk,i-1) end
 buffer[#buffer+1]=repl
 oldk=j+1
 n=n-1
 if n==0 then break end
 end
 return table.concat(buffer)..s:sub(oldk,#s)
end
> a="abcdefgbcgfhjtubc"
> return a:rawgsub("bc","BC",2) --> aBCdefgBCgfhjtubc

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