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,
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
true; otherwise it returns
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
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; ...