Ruby Regular Expressions: The Complete Tutorial

Ruby Regular Expressions: The Complete Tutorial

Ruby regular expressions (ruby regex for short) help you find specific patterns inside strings, with the intent of extracting data for further processing.

Ruby regular expressions (ruby regex for short) help you find specific patterns inside strings, with the intent of extracting data for further processing.

Two common use cases for regular expressions include validation & parsing.

For example:

Think about an email address, with a ruby regex you can define what a valid email address looks like. In other words, your program will be able to tell the difference between a valid & invalid email address.

ruby regex

Ruby regular expressions are defined between two forward slashes to differentiate them from other language syntax. The most simple expressions match a word or even a single letter.

For example:

  1. Find the word 'like'

  2. "Do you like cats?" =~ /like/

This returns the index of the first occurrence of the word if it was found or nil otherwise. If we don’t care about the index we could use the String#include? method.

Another way to check if a string matches a regex is to use the match method:

if "Do you like cats?".match(/like/)
  puts "Match found!"
end

Now you are going to learn how to build more advanced patterns so you can match, capture & replace things like dates, phones numbers, URLs, etc.

Character Classes

A character class lets you define a range or a list of characters to match. For example, [aeiou] matches any vowel.

Example: Does the string contain a vowel?

def contains_vowel(str)
  str =~ /[aeiou]/
end

contains_vowel("test") ## returns 1
contains_vowel("sky")  ## returns nil

This will not take into account the amount of characters, we will see how to do that soon.

Ranges

We can use ranges to match multiple letters or numbers without having to type them all out. In other words, a range like [2-5] is the same as [2345].

Some useful ranges:

  • [0-9] matches any number from 0 to 9
  • [a-z] matches any letter from a to z (no caps)
  • [^a-z] negated range

Example: Does this string contain any numbers?

def contains_number(str)
  str =~ /[0-9]/
end

contains_number("The year is 2015")  ## returns 12
contains_number("The cat is black")  ## returns nil

Remember: the return value when using =~ is either the string index or nil

There is a nice shorthand syntax for specifying character ranges:

  • \w is equivalent to [0-9a-zA-Z_]
  • \d is the same as [0-9]
  • \s matches white space (tabs, regular space, newline)

There is also the negative form of these:

  • \W anything that’s not in [0-9a-zA-Z_]
  • \D anything that’s not a number
  • \S anything that’s not a space

The dot character . matches everything but new lines. If you need to use a literal . then you will have to escape it.

Example: Escaping special characters

## If we don't escape, the letter will match
"5a5".match(/\d.\d/)

## In this case only the literal dot matches
"5a5".match(/\d\.\d/) ## nil
"5.5".match(/\d\.\d/) ## match

ruby regex ruby-on-rails programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Ruby on Rails Developer | Hire RoR Developer

#1 Ruby on Rails development company. Hire Ruby on rails developer or a team to build secure, scalable and complex web solutions with a quick turnaround time.

"Rewrite your Software," says Creator of Ruby on Rails

David Heinemeier Hansson is the creator of Ruby on Rails, co-founder & CTO of Basecamp, best-selling author, Le Mans class-winning race car driver, family man, frequent podcast guest, and inspirational conference speaker.

Hire Ruby on Rails Developers

![Hire Ruby on Rails Developers](https://semidotinfotech.com/storage/uploads/service/hire-ruby-on-rails-developers.jpg "Hire Ruby on Rails Developers") [Hire ruby on rails developers](https://semidotinfotech.com/hire-ruby-on-rails-developers...

Why Ruby on Rails(RoR) is still a good choice in 2020.

Ruby on Rails in 2020: Reasons why RoR is still a viable technology in 2020 to bring your business app ideas to life with examples.

How to Deploy a Ruby on Rails App on Heroku

The most satisfying thing beyond building something is to make it available to the world. Heroku is great for beginners because it’s a free and “simple” push-to-deploy system.