lua-users home
lua-l archive

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

On 27/08/2019 14.46, Scott Morgan wrote:
On 27/08/2019 10:44, Luiz Henrique de Figueiredo wrote:
On Tue, Aug 27, 2019 at 5:55 AM Scott Morgan <> wrote:

What's the best way to filter out non-specified chars from an ASCII
string? (so no need to worry about UTF8, etc.)

local allowed = "AbC"
local txt = "dDcCbBaA"

filter(txt, allowed, "") -- ret: "CbA"
filter(txt, allowed, "?") -- ret: "???Cb??A"

function filter(t,a,r)

Doh! Knew I was missing something simple, hence the question.

Is there a limit to how big those sets can be? In practice I'd be
looking at a few dozen allowed chars.

Even if you put in all possible byte values it works:

    s = "["
    for i = 0, 255 do  s = s .. "%" .. string.char( i )  end
    s = s .. "]"
    for m in ("xyzzy"):gmatch( s ) do  print( m )  end
    --> x y z z y
    for m in ("xyzzy"):gmatch( "[^"..s:sub(2,-1) ) do  print( m )  end
    --> (nothing)

(And yes always putting in the escaping '%' works fine and is probably safer/simpler than a bunch of special cases if you're generating the set…)

-- nobody