Erlang Central

String Filter For Character Set

Revision as of 21:53, 3 September 2006 by Bfulgham (Talk | contribs)

Problem

You want to remove all but a specified set of characters from a string.

Solution

This is really a extension of what we talked about in StringCheckForChar. The Erlang lists module provides several functions that allow manipulations of strings (since they are simply lists of characters). For example, to remove non-letters from a string, we could define a predicate that recognizes only letters:

1> lists:filter(fun(X) -> lists:member(X, 
1>     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") end,
1>     "Hello, World!").
"HelloWorld"
37> lists:filter(fun(X) -> not lists:member(X,
37> "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") end,
37> "Hello, World!").
", !"