[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Extending lpeg's gsub example
- From: Sean Conner <sean@...>
- Date: Fri, 29 Nov 2019 17:29:10 -0500
It was thus said that the Great Marcus Mason once stated:
> I'd like to extend this example so that I can specify the maximum
> number of replacements as in normal string.gsub
> function gsub (s, patt, repl)
> patt = lpeg.P(patt)
> patt = lpeg.Cs((patt / repl + 1)^0)
> return lpeg.match(patt, s)
> What would be the best way to achieve this?
Here's one way that works:
lpeg = require "lpeg"
n = n or math.maxinteger
local match = 0
patt = lpeg.Cmt(lpeg.P(patt),function(sub,pos,cap)
if n == 0 then
match = match + 1
n = n - 1
patt = lpeg.Cs((patt / repl + 1)^0)
return lpeg.match(patt, s),match
test = "abcabcabcabcabc"
lpeg.Cmt() does a compile-time match and it's here that we track the
number of matches. I also added the second return (number of successful
matches) to match string.gsub().