Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 48 ยท Enumerables and Data Processing

Sigils and Regular Expressions

Learn Elixir sigils such as ~r, ~s, ~w and ~D, the Regex module, named captures, replacing text, modifiers and how to write your own custom sigil.

A sigil is a compact way to write a value that would be awkward to write with ordinary quotes. It starts with a tilde, then one letter that says what kind of value you want, then the content between delimiters: ~w(red green blue) is a list of three strings, and ~r/\d+/ is a regular expression. The most common sigils make strings, word lists, regular expressions, dates and times.

Regular expressions are the headline use. This lesson shows the built-in sigils, then the Regex module: testing, extracting, naming captures and replacing text. It follows strings and binaries and uses pattern matching on the results. At the end you will define a sigil of your own.

Elixir is not installed on this site, so the Elixir code below is read-only. The runnable examples use JavaScript regular expressions as a stand-in. JavaScript and Elixir regexes are similar but not identical (Elixir uses Perl-compatible syntax, and its functions return tuples and lists, not match objects), so the stand-ins show the ideas, not the exact Elixir output.

The anatomy of a sigil

ELIXIR
~s(She said "hello")        # a string; quotes need no escaping
~w(red green blue)          # ["red", "green", "blue"]
~w(red green blue)a         # [:red, :green, :blue]
~r/colou?r/i                # a regex, case-insensitive
~D[2026-03-01]              # a Date struct

After the closing delimiter you may add modifiers, single letters that tune the result. Elixir accepts eight delimiters: / | " ' ( ) [ ] { } < >. Pick the one that does not appear in your content, so you avoid escaping. A regex for a path reads best as ~r|/users/\d+|.

The case of the letter matters:

  • Lowercase sigils (~s, ~w, ~r) support interpolation (#{...}) and escape codes like \n.
  • Uppercase sigils (~S, ~W, ~R) take the text exactly as typed, with no interpolation and no escapes.
ELIXIR
name = "Ada"
~s(Hello #{name}\n)    # "Hello Ada\n"
~S(Hello #{name}\n)    # "Hello \#{name}\\n"  (the text, untouched)

Sigils also work with heredoc triple quotes (~s"""), which is useful for long multi-line text.

Common built-in sigils

~s / ~S A string, with or without interpolation.
~w / ~W A list of words split on whitespace.
~r / ~R A regular expression.
~D ~T ~N ~U Date, Time, NaiveDateTime, UTC DateTime.

Lowercase interpolates. Uppercase keeps the text raw.

1 / 2

Word lists, dates and times

~w splits on whitespace and saves a lot of quotes. Modifiers pick the element type: s strings (the default), a atoms, c charlists.

The date and time sigils check their content when the code is compiled, so a typo such as ~D[2026-13-01] is caught before the program runs:

ELIXIR
date = ~D[2026-03-01]
date.year                        # 2026
Date.add(date, 30)               # ~D[2026-03-31]
~T[14:30:00]                     # a Time
~N[2026-03-01 14:30:00]          # NaiveDateTime, no time zone
~U[2026-03-01 14:30:00Z]         # DateTime in UTC

Regular expressions with ~r

A regex describes a pattern of text. You write it with ~r, and the functions in the Regex module apply it. The =~ operator is a quick yes/no test:

ELIXIR
"order 4521 shipped" =~ ~r/\d+/        # true
"order shipped" =~ ~r/\d+/             # false
Regex.match?(~r/^[a-z]+$/, "hello")    # true

Common modifiers go after the closing slash:

Modifier Effect
i Ignore case
m ^ and $ match at every line, not just the string ends
s . also matches a newline
x Extended: whitespace and # comments inside the pattern are ignored
u Unicode-aware matching (\p{L}, and \w match non-ASCII letters)

The x modifier lets you document a complicated pattern:

ELIXIR
~r/
  (\d{4})   # year
  -
  (\d{2})   # month
/x

Because the regex is compiled once when the module compiles, it costs nothing at runtime to repeat ~r in a function body. Reach for Regex.compile/2 only when the pattern comes from user input or configuration.

Finding and extracting

Regex.run/2 returns the first match as a list, with the whole match first and then each capture group. Regex.scan/2 returns every match:

ELIXIR
Regex.run(~r/(\d+)-(\d+)/, "range 10-25 and 30-40")
# ["10-25", "10", "25"]

Regex.scan(~r/\d+/, "a1 b22 c333")
# [["1"], ["22"], ["333"]]

Regex.scan(~r/\d+/, "a1 b22 c333") |> List.flatten()
# ["1", "22", "333"]

Each scan result is itself a list, because a match may carry capture groups. Regex.run/2 returns nil when there is no match, so handle both outcomes, ideally with case or multiple clauses.

Named captures

Numbered groups become hard to read. Name them with (?<name>...) and use Regex.named_captures/2, which returns a map with string keys, or nil:

ELIXIR
pattern = ~r/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/

Regex.named_captures(pattern, "released 2026-03-01 (beta)")
# %{"year" => "2026", "month" => "03", "day" => "01"}

case Regex.named_captures(pattern, input) do
  %{"year" => y, "month" => m} -> "#{m}/#{y}"
  nil -> "no date found"
end

Values are always strings, so convert them with String.to_integer/1 when you need numbers.

JS Named captures and scan, JavaScript stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Replacing and splitting

Regex.replace/3 swaps every match. In the replacement, \\1 refers to the first capture group (write \\1 inside a normal string, or \1 inside a ~S sigil). Regex.replace/4 with global: false replaces only the first:

ELIXIR
Regex.replace(~r/(\w+)@(\w+)\.com/, "mail [email protected] now", "\\1 at \\2")
# "mail ann at site now"

Regex.replace(~r/\s+/, "too    many   spaces", " ")
# "too many spaces"

Regex.replace(~r/\d/, "a1b2", "#", global: false)
# "a#b2"

The replacement can also be a function that receives the whole match, which is the tool for transformations:

ELIXIR
Regex.replace(~r/\d+/, "3 apples, 12 pears", fn n ->
  Integer.to_string(String.to_integer(n) * 2)
end)
# "6 apples, 24 pears"

String.split/2 also accepts a regex, and String.replace/3 accepts one as the pattern: String.split("a, b;c", ~r/[,;]\s*/) gives ["a", "b", "c"].

A regex is a poor fit for nested or recursive formats such as HTML, JSON or full email address validation. Use a real parser for those, and keep regexes for simple, flat patterns. Also beware of catastrophic backtracking: a pattern like (a+)+$ can take exponential time on hostile input, so never run an untrusted pattern or apply a complex one to unbounded user text.

Your own sigil

Any function named sigil_x (lowercase) or sigil_X (uppercase letter) defines a sigil. It receives the text between the delimiters, as a string, and a charlist of modifiers. The sigil is found like any imported function, so the module that defines it must be imported where you use it:

ELIXIR
defmodule MySigils do
  # ~u"..." splits a string on commas and upcases every part
  def sigil_u(text, []), do: text |> String.split(",") |> Enum.map(&String.upcase/1)
  def sigil_u(text, [?t]), do: text |> String.split(",") |> Enum.map(&String.upcase(String.trim(&1)))
end

import MySigils
~u(a,b,c)       # ["A", "B", "C"]
~u(a, b, c)t    # ["A", "B", "C"]

The first clause matches no modifiers ([]) and the second matches the t modifier (?t is the character code for t). Custom sigils are nice for small domain-specific literals such as money (~M[10.50 USD]), paths or validated identifiers. Do not overuse them: a plain function call is often clearer.

JS A tiny sigil-like helper in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between ~s(...) and ~S(...)?

    Lowercase sigils interpolate #{...} and process escapes such as \n. Uppercase sigils take the content raw.
  2. 2. What does Regex.scan(~r/\d+/, "a1 b22") return?

    scan returns a list of matches, and each match is a list because it can hold capture groups. Use List.flatten/1 when there are none.
  3. 3. What does Regex.named_captures/2 return when the pattern does not match?

    It returns nil for no match, and a map with string keys otherwise, so case is the natural way to handle both.
  4. 4. Which line makes [:red, :green] from a word list?

    The a modifier turns each word into an atom. Without a modifier, or with s, you get strings.

Summary

  • A sigil is ~, a letter, delimiters and optional modifiers; lowercase interpolates, uppercase is raw.
  • ~w builds word lists, ~D, ~T, ~N and ~U build checked date and time values, and ~r builds a regular expression.
  • =~ and Regex.match?/2 test; Regex.run/2 and Regex.scan/2 extract; Regex.named_captures/2 gives a map or nil.
  • Regex.replace/3 supports \\1 references and replacement functions.
  • Define your own with sigil_x/2, but keep it for small literals.
  • Avoid regexes for nested formats and watch for catastrophic backtracking.

Next, learn how Elixir programs deal with failure: Error Handling: Tuples, with and Exceptions.