Regular expressions

A regular expression is a pattern written as a string and compiled to a matcher. In Elixir it is built with the sigil ~r, it has its own type, Regex, and the module of the same name answers the four questions a program asks: is there a match, what is the first one, what are all of them, and how is the text rewritten.

run: the first match

Regex.run/2 answers the first match as a list: the whole match first, then every capture group in the order of its parentheses. The capture: :all_but_first option drops the whole match when only the groups matter:

run.exs

IO.inspect(Regex.run(~r/(\d+)-(\d+)/, "10-20")) IO.inspect(Regex.run(~r/(\d+)-(\d+)/, "10-20", capture: :all_but_first)) IO.inspect(Regex.run(~r/x/, "abc")) IO.inspect(Regex.match?(~r/^\d+$/, "123"))

elixir run.exs

["10-20", "10", "20"]
["10", "20"]
nil
true

No match is nil, which a program branches on rather than crashing: the tuple pattern of case reads well here. Regex.match?/2 is the shorter call when the question is only whether the text fits, and the anchors ^ and $ make it a test of the whole string rather than of a part of it.

scan and split

Regex.scan/2 answers every match as a list of lists, each one holding the whole match and its groups. String.split/2 takes a pattern as its separator, which is the shortest way to cut a line on a run of digits:

scan.exs

IO.inspect(Regex.scan(~r/\w+/, "a bb ccc")) IO.inspect(Regex.scan(~r/(\w+)=(\w+)/, "a=1 b=2")) IO.inspect(String.split("a1b22c", ~r/\d+/))

elixir scan.exs

[["a"], ["bb"], ["ccc"]]
[["a=1", "a", "1"], ["b=2", "b", "2"]]
["a", "b", "c"]

The first line is the shape to remember: a pattern with no group still answers one list per match. Regex.scan/3 takes the same capture: option as run/3, and return: :index gives the byte positions instead of the text.

replace and the capture groups

Regex.replace/4 rewrites every match with a replacement string, and a backslash and a number in that string stand for a capture group:

replace.exs

IO.inspect(Regex.replace(~r/\s+/, "a b", " ")) IO.inspect(Regex.replace(~r/(\w+)@(\w+)/, "ada@example", "\\2:\\1"))

elixir replace.exs

"a b"
"example:ada"

The backslash is written twice because it is also the escape of the Elixir string, so "\2" reaches the regex engine as \2. A replacement that needs the match itself uses \0, and a function may be given as the replacement when the new text is computed rather than written, which is the form of a rewriter that changes case or numbers.

A named capture

A group may be named in the pattern with (?<name>...), and Regex.named_captures/2 answers a map from the name to the text. The map is the reason to use a name: a program reads the key it means rather than counting parentheses:

named.exs

case Regex.named_captures(~r/(?<user>\w+)@(?<host>\w+)/, "ada@example") do %{"user" => user, "host" => host} -> IO.inspect({user, host}) nil -> IO.puts("no match") end

elixir named.exs

{"ada", "example"}

The pattern is read as an email address, and the two keys are the parts. A named capture is still a group for run/2 and scan/2, which keep the order of the parentheses; the names are the extra for the reader.

The mistake: a pattern that does not compile

The sigil compiles its pattern when the module is compiled, so a broken pattern is an error of the program rather than a value it can test. An unclosed character class stops it with a Regex.CompileError that gives the position:

mistake.exs

IO.inspect(Regex.run(~r/[a-/, "abc"))

elixir mistake.exs

** (Regex.CompileError) missing terminating ] for character class at position 3
    (elixir 1.19.7) lib/regex.ex:251: Regex.compile!/2
    (elixir 1.19.7) lib/kernel.ex:6649: Kernel.compile_regex/2
    (elixir 1.19.7) expanding macro: Kernel.sigil_r/2
    mistake.exs:1: (file)

A pattern that arrives as data is the case for Regex.compile/2, which answers an :ok or an :error tuple and lets the program report a bad rule instead of crashing at start-up. The sigil is for the patterns the code owns, and those are tested by the examples of the module.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Regex.run/2 answer when the pattern does not match?

    Answer

    nil

    No match is nil, and a program branches on it rather than on an empty value.

  2. What does the first item of the list Regex.run/2 answers hold?

    Answer

    the whole match

    The whole match comes first and the groups follow in the order of the parentheses.

  3. What does capture: :all_but_first do?

    Answer

    It drops the whole match and keeps the groups

    The option is the one a program uses when it wants the parts and not the whole text.

  4. Why is the backslash of a replacement written twice?

    Answer

    because the Elixir string uses the backslash as its own escape

    The string literal turns \\ into one backslash, which is what the regex engine sees.

  5. What does this program print? IO.inspect(Regex.run(~r/(\d+)-(\d+)/, "10-20"))

    Answer

    ["10-20", "10", "20"]

    The whole match comes first, then the two groups in the order they appear.

  6. What does this program print? IO.inspect(Regex.scan(~r/\w+/, "a bb"))

    Answer

    [["a"], ["bb"]]

    scan answers one list per match, and a pattern with no group still has one item per match.

  7. What does this program print? IO.inspect(Regex.match?(~r/^\d+$/, "123"))

    Answer

    true

    The anchors make the digits the whole string, and 123 fits.

  8. What does this program print? IO.inspect(Regex.replace(~r/\s+/, "a b", " "))

    Answer

    "a b"

    The run of spaces is one match and becomes one space.

  9. What does this program print? IO.inspect(Regex.named_captures(~r/(?<user>\w+)@(?<host>\w+)/, "ada@example"))

    Answer

    %{"host" => "example", "user" => "ada"}

    The named captures come back as a map from each name to its text.

  10. What does this program do? IO.inspect(Regex.run(~r/[a-/, "abc"))

    Answer

    A Regex.CompileError, because the character class is not closed

    The sigil compiles the pattern at compile time, and an unclosed class is a compile error.

Article author: Arthur Isaev