- Read Tutorial
- Watch Guide Video
I think you're going to enjoy this guide since we are going to walk through a practical example of using regular expressions. In this guide we are going to check if a particular string is a valid email address or not. In fact, I pulled this out of one of my Rails applications so you can get a hands-on feel of Ruby programming in a real world program.
REGEX Code Example
To start let's create a constant variable that stores our regular expression. Now I'm not going to go into detail with describing how each expression works because this is not a Regular Expressions course (and entire books have been written dedicated solely to regular expressions). Instead, we'll focus on how to use them in Ruby. There are countless resources with Regex cheat sheets that you can incorporate for matchers.
Here is the regular expression code that will verify that a string matches the common pattern followed by email addresses.
VALID_EMAIL_REGEX = /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
If you look at this expression, the first part allows names, numbers, dashes and dots. This is followed by ensuring that the @
symbol is used. Next it verifies that letters and numbers follow the @
symbol. And lastly this is followed by a .
and letters. So, this typically is in the format something@domain.extension
. At the end, we are ensuring that the matcher is case insensitive with /i
.
Next, we are going to build a method that verifies this pattern.
def is_valid_email? email email =~ VALID_EMAIL_REGEX end
In this code we are creating a method called is_valid_email?
and we are passing an argument called email
.
Next, we are checking this parameter against the VALID_EMAIL_REGEX
constant to return true
or false
.
Now, let's check some use cases.
p is_valid_email?("jordan@hudgens.com") ? "Valid" : "Invalid" p is_valid_email?("jordanhudgens.com") ? "Valid" : "Invalid" p is_valid_email?("jordan.h@hudgens.com") ? "Valid" : "Invalid" p is_valid_email?("jordan@hudgens") ? "Valid" : "Invalid"
If you execute this code, your output should be:
"Valid" "Invalid" "Valid" "Invalid"
So, the first and third email addresses are valid because they match our pattern, while the second and fourth are invalid.
devCamp Note: when you're using a ternary operator, you have to enclose your arguments in parentheses.
Let's try one more use case:
p is_valid_email?("jordan_h@hudgens.net") ? "Valid" : "Invalid"
If you run it, the output is Valid
, so the application is accepting the _
symbol in addition to dashes.
This is how you can integrate our regular expression email validator code in a Ruby on Rails application:
So by leveraging regular expressions we're able to do something complex, such as checking an email address with only a few lines of code. Without regular expressions, you would probably be writing hundreds of lines of code to check against every possibility.