Regex
September 24, 2023 1 minutes • 122 words
Table of contents
The ~r
sigil creates Regex. These are used to find matching patterns in a string.
Regex Functions
Function | Description |
---|---|
Regex.scan/3 |
Lists the matches |
Regex.run/3 |
Runs regex until the first match |
Regex.replace/4 |
Replaces all matches |
Regex.split/3 |
Split the string on matches |
Regex.match?/2 |
Does the string have the regex? |
.scan/3 | Description | Example |
---|---|---|
1 |
Sigil | ~r |
2 |
Regex | /l/ |
3 |
Data | `“hello”`` |
Regex.scan(~r/l/, "hello")
# [["l"], ["l"]]
Regex.scan(~r/\d/, "h3ll0")
# [["3"], ["0"]]
Elixir uses the PCRE standard (Perl Compatible Regular Expressions).
Common Regex are
Regex | Description |
---|---|
\d |
any digit from 0-9 |
\w |
word character, any single letter, number, or underscore |
. |
non-newline character (essentially anything) |
\s |
whitespace character |
Capitalizing backslash characters inverts their purpose.
Regex | Description |
---|---|
\D |
non-digit character |
\W |
non-word character |
\S |
non-whitespace character |