Regular Expressions

Flashcard 8 of 10

How can we select only the elements in an array that match a given regex?

valid_email = /.+@.+\..+/

possible_emails = [
  "user@example.com",
  "person@thing",
  "ben@upcase.com",
  "user@place.it",
  "asdf"
]

<your code here, using valid_email>
#=> [
#     "user@example.com",
#     "ben@upcase.com",
#     "user@place.it"
#   ]

As luck would have it, Array has a #grep method which compares each element in the array to a pattern and returns only elements that match the pattern:

valid_email = /.+@.+\..+/

possible_emails = [
  "user@example.com",
  "person@thing",
  "ben@upcase.com",
  "user@place.it",
  "asdf"
]

possible_emails.grep(valid_email)
#=> [
#     "user@example.com",
#     "ben@upcase.com",
#     "user@place.it"
#   ]

Note: Array#grep is essentially a shorthand for:

possible_emails.filter do |email|
  email =~ pattern
end

Final Note: The above pattern for a "valid email address" is very simplistic and only asserts "one or more characters, then an @ symbol, one or more characters, a literal '.', one or more characters." While simple, the official version is unreasonably complex and I prefer to use the above to avoid false negatives.

Return to Flashcard Results