lua-users home
lua-l archive

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


Scott:

On Tue, Aug 27, 2019 at 10:55 AM Scott Morgan <blumf@blueyonder.co.uk> wrote:
> What's the best way to filter out non-specified chars from an ASCII
> string? (so no need to worry about UTF8, etc.)

> filter(txt, allowed, "") -- ret: "CbA"
> filter(txt, allowed, "?") -- ret: "???Cb??A"
>
> For extra difficulty, plain Lua 5.1, no modules (lpeg, etc.)
>
> I can see a way using gsub(txt, ".", filter_func), but was wondering if
> there are any tricks that might make it simpler.

With your examples it seems building a char-set from the allowed chars
and using gsub will do the trick, i.e.:

string.gsub(txt, build_charset(allowed), repl)

> string.gsub("12345678", "[^246]", "")
246    5
> string.gsub("12345678", "[^246]", "?")
?2?4?6??    5

Then, to build the charset, you just have to filter a couple of
special chars ( take care of detecting % and - in allowed and escape
them ) ( I'm not too sure if you need to escape a leading ^ too, but a
couple oneliners would reveal it ).

Francisco Olarte.