Replacing string codepoints with patterns
In this recipe, we will demonstrate how to replace codepoints in a string using a match pattern. We will use the String.replace/4
function to help with this task.
Note
A codepoint, in this context, is the binary representation of a UTF-8 encoded character.
Getting ready
This recipe will be performed inside an IEx session. Start it by executing the iex
command in your command line.
How to do it…
To find a pattern in a string and replace it, follow these steps:
- Define a string:
iex(1)> my_string = "user1@server.domain user2@server.domain" "user1@server.domain user2@server.domain"
- Define a string pattern to use with
String.replace
:iex(2)> my_pattern = "@" "@"
- Perform the replacement using the default options:
iex(3)> String.replace(my_string, my_pattern, "(at)") "user1(at)server.domain user2(at)server.domain"
- Perform the replacement only at the first pattern occurrence:
iex(4)> String...