Regular Expressions in Elixir

Our first program will demonstrate common regular expression tasks in Elixir. Here’s the full source code:

defmodule RegexExample do
  def run do
    # This tests whether a pattern matches a string.
    match = Regex.match?(~r/p([a-z]+)ch/, "peach")
    IO.puts(match)

    # For other regex tasks, we'll use a compiled Regex struct.
    r = ~r/p([a-z]+)ch/

    # Here's a match test like we saw earlier.
    IO.puts(Regex.match?(r, "peach"))

    # This finds the match for the regex.
    IO.puts(Regex.run(r, "peach punch") |> List.first())

    # This returns the start and end indexes for the match.
    case Regex.run(r, "peach punch", return: :index) do
      [{start, length}|_] -> IO.puts("idx: [#{start} #{start + length}]")
      nil -> IO.puts("No match")
    end

    # The :all option includes information about both the whole-pattern 
    # matches and the submatches within those matches.
    IO.inspect(Regex.run(r, "peach punch", capture: :all))

    # Similarly, this will return information about the indexes of matches and submatches.
    IO.inspect(Regex.run(r, "peach punch", return: :index, capture: :all))

    # To find all matches for a regex:
    IO.inspect(Regex.scan(r, "peach punch pinch"))

    # Providing a non-negative integer as the third argument will limit the number of matches.
    IO.inspect(Regex.scan(r, "peach punch pinch", return: :index) |> Enum.take(2))

    # The regex package can also be used to replace subsets of strings with other values.
    IO.puts(Regex.replace(r, "a peach", "<fruit>"))

    # The :replace option allows you to transform matched text with a given function.
    IO.puts(Regex.replace(r, "a peach", fn _, match -> String.upcase(match) end))
  end
end

RegexExample.run()

To run the program, save it as regex_example.exs and use elixir:

$ elixir regex_example.exs
true
true
peach
idx: [0 5]
["peach", "ea"]
[{0, 5}, {1, 2}]
[["peach", "ea"], ["punch", "un"], ["pinch", "in"]]
[{0, 5}, {6, 5}]
a <fruit>
a PEACH

In Elixir, regular expressions are represented using the ~r sigil. The Regex module provides functions for working with regular expressions.

Unlike Go, Elixir doesn’t have separate functions for string and binary operations on regular expressions. The same functions work for both.

Elixir’s Regex.run/3 and Regex.scan/3 functions are quite versatile and can be used to achieve the functionality of various Go regex functions by using different options.

For a complete reference on Elixir regular expressions, check the Regex module docs.