Replace applied to atoms

Hello,

I have an atom that can have spaces included such as ‘abc def ghj’.

I now need to generate a new atom (or string) out of this with all spaces replaced by underscores.

I can’t find a replace predicate – typically found in, for example, string libraries.

Is there a simple (and efficient) way to do such a replace.

thanks,

Dan

I think to do that sort of thing, it’s easiest to convert to a string, use the string manipulation functions, then convert back to an atom. That’s been my experience, at least…

102 ?- re_replace(' '/a, '_', 'hello world', X).
X = hello_world.

See docs for re_replace/4 for details.

1 Like

I was not aware of this predicate and it’s really useful!
Only a minor comment: for Dan’s use case I think the flag is /g instead of /a: re_replace(' '/g, '_', 'abc def ghj', X).

Thanks. You need both (/ga) as g main replace all and a means return the result as an atom ) (instead. of the default string).

Note that for this particular case we can also do

split_string(In, " ", "", Parts),
atomics_to_string(Parts, "_", S),
atom_string(Out, S).

The advantage is that you do not rely on the pcre package. Didn’t test the relative performance. I would expect both these are considerably faster than the route via atom_codes/2. That route is attractive for more complicated rewrites where DCGs start to show there power and for portability.