Table of contents
1.
Introduction
2.
Regular Expressions in Ruby
2.1.
Syntax
3.
=~ and #match operators
4.
Meta Characters and Escapes 
5.
Characters Classes 
6.
Quantifiers
7.
Frequently Asked Questions
7.1.
What is regex?
7.2.
What is a delimiter?
7.3.
Where are textual patterns utilised?
7.4.
What are Expression and Operator?
7.5.
What are the uses of regular expressions in Ruby?
8.
Conclusion
Last Updated: Mar 27, 2024

Regular Expressions in Ruby

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ruby

In this blog, we will see about regular expressions in ruby. A regular expression is a sequence of characters, often known as regex or regexp, that describes a search pattern in the text. Such patterns are typically utilised by string-searching algorithms for input validation or 'find' or 'find-and-replace' operations on strings.

So, now let us learn about regular expressions in ruby in detail.

Start Image

Regular Expressions in Ruby

A regular expression describes a textual pattern. Regular expressions in ruby are implemented by the Regexp class. Regexp and String both define operators and methods for pattern matching. Most languages support regular expressions, and Ruby's Regexp syntax resembles Perl 5's syntax somewhat (though not precisely).

Ruby regular expressions (ruby regex for short) allow you to find specific patterns within strings and extract data for further processing.

Validation and parsing are two common applications for regular expressions.

For example:

Think about an email address; a ruby regex can be used to define what a valid email address looks like. In other words, your program will be able to distinguish between valid and invalid email addresses.

Ruby Regex

To distinguish them from other language syntax, Ruby regular expressions are defined between two forward slashes. The most basic expressions correspond to a word or even a single letter.

Syntax

/search string/
You can also try this code with Online Ruby Compiler
Run Code

=~ and #match operators

The pattern matching is achieved by =~ and #match operator.

Let us discuss them in detail:

=~ operator 

The first is a regular expression, and the second is a string. The string is matched with the regular expression.

If a match is found, the operator returns the index of the first match; otherwise, it returns nil.
 

For example:
 

# Find the word 'Ninja'
puts "Are you a Ninja?" =~ /Ninja/ 
You can also try this code with Online Ruby Compiler
Run Code

 

Output 

output

Explanation

This returns the index of the first occurrence of the matched word, if not matched nil is returned. Henceforth, 10 is returned!

Let us one more example: 
 

# Find the word 'Coder’'
puts "Are you a Ninja?" =~ /Coder/   #nil
You can also try this code with Online Ruby Compiler
Run Code

 

#match operator 

If a match is found, this operator returns a MatchData object; otherwise, it returns nil.
 

For example:

# Find the word 'Coder'
puts /coder/.match("Are you a coder?")
You can also try this code with Online Ruby Compiler
Run Code

 

Output

output

Meta Characters and Escapes 

In a pattern, metacharacters have a specific meaning. They are back slashed (\) or escaped to match a string.

Some meta characters are (,), (.), (?), (+), (-), (*), [,], {,}.
 

When a match is found, it returns the specific string; otherwise, it returns nil.
 

For example:
 

puts /Hello\! I am new here\./.match("Ninja here, Hello! I am new here.")
puts /3 \* 4 \+ 5 = \?/.match("3 * 4 + 5 = ?")
puts /3 * 4 + 5 = ?/.match("3 * 4 + 5 = ?")
You can also try this code with Online Ruby Compiler
Run Code

 

Output

output

Characters Classes 

Metacharacters have specific meaning in a pattern. To match a string, they are back slashed (\\\) or escaped.

A character class is encircled within square brackets.

[pq..]

Here, [pq] denotes either p or q. It is the inverse of /pq/, which stands for p and q.

For example:

puts /C[aeivo]ding/.match("Coding Ninjas")
puts /C[aei]ding/.match("Coding Ninjas")
You can also try this code with Online Ruby Compiler
Run Code

 

Output

Output

[p - s]

 

  • Here, [p-s] is equivalent to [pqrs]. 
  • The hyphen (-) character class represents a range of characters.
     

For examples:

 

puts /[a-d]/.match("Java")
puts /[p-s]/.match("Pythonista")
puts /[L-P]/.match("Programmer")
You can also try this code with Online Ruby Compiler
Run Code

 

Output

Out

[^p-s]

The ^ sign represents any other character that is not present in the range.

puts /[^a-rs-z]/.match("Ga")
puts /[^a-fe-p]/.match("Pys")
puts /[^L-P]/.match("Pro")
You can also try this code with Online Ruby Compiler
Run Code

 

Output

Output

So far we’ve discussed pattern matching for single characters. With the help of repetition metacharacter, we can specify how many times they need to occur. These meta characters are called quantifiers.

Quantifiers

Quantifiers allow you to specify the count of repeated strings.

Quantifiers in Ruby

Check out this problem - Shortest Common Supersequence.

Frequently Asked Questions

What is regex?

The regex or regexp is the acronym for 'regular expression', which is a sequence of characters that describes a search pattern in the text.

What is a delimiter?

One or more characters which divide text strings are known as delimiters. Commas (,), semicolons (;), quotes (", "), braces (), pipes (|), and slashes (/) are common delimiters.

Where are textual patterns utilised?

Textual patterns are typically utilised by string-searching algorithms for input validation or 'find' or 'find-and-replace' operations on strings.

What are Expression and Operator?

An expression is a section of Ruby code that the Ruby interpreter can evaluate to produce a value. An operator is a token or a particular symbol in the Ruby language representing an operation (such as addition or comparison) performed on one or more operands.

What are the uses of regular expressions in Ruby?

A string of characters known as a regular expression defines a search pattern, typically used in string pattern matching. Regular expressions in ruby help us to search for specific patterns within strings. Validation and parsing are two applications of ruby regex.

Conclusion

This article extensively discussed Regular Expressions in Ruby. We started with a brief introduction to regular expression and then learnt about regex literals, regex factory methods, regex syntax and pattern matching with regular expression.

After reading about Regular Expressions in Ruby, are you not feeling excited to read/explore more articles on the topics related to Ruby?. To learn, see History of Rubyeight reasons why Ruby should be your first languageRuby vs PythonDocumentation of RubyOfficial Ruby FAQ, and Learn Ruby with the Edgecase Ruby Koans.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Ninjas Logo

Live masterclass