Appendix B. A Brief Introduction to Regular Expressions

If there’s one thing that humans do well, it’s recognizing patterns. Most people from the United States can categorize the numbers in the following list as a social security number, a phone number, a date, and a postal code.

321-40-0909
302-555-8754
3-15-66
95124-0448

You can tell at a glance which of the following words can’t possibly be valid English words by the pattern of consonants and vowels:

grunion vortenal pskov trebular elibm talus

Regular expressions are Elixir’s method of letting your program look for patterns; for example,

  • A fraction is a series of digits followed by a slash, followed by another series of digits.
  • A valid name consists of a series of letters, a comma followed by zero or more spaces, followed by another series of letters.

The Simplest Patterns

Throughout this tutorial you’ll be using the Regex.match?/2 function. Its first argument is a regular expression pattern, and the second argument is the string you want to test against. If the pattern matches the string, the function returns true; otherwise it returns false.

To create a pattern, you use the string sigil ~r followed by the pattern, enclosed in slashes. Here is an IEx session that tests to see if the string "hello" contains the letter e, and then tests to see if it contains the letter u.

iex(1)> Regex.match?(~r/e/, "hello")
true
iex(2)> Regex.match?(~r/u/, "hello")
false

A pattern match will find the pattern if it exists anywhere within the string; ...

Get Études for Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.