Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby

What are regular expressions in Ruby?

Sheza Munir

Regular expressions in Ruby are user-determined strings that we can use for pattern-matching in a text. We use these patterns to determine whether the ‘target’ string has the characteristics defined in the pattern.

Modifiers

Modifier

Description

i

This modifier makes the pattern matching case-sensitive.

o

This modifier makes sure that the pattern is only matched once.

x

This modifier allows the use of whitespace in the pattern.

m

This modifier matches multiple lines.

u,e,s,n

These modifiers interpret the expression as Unicode (UTF-8), EUC, SJIS, or ASCII. By default, the regular expression is assumed to use the source encoding.

Definition

We define the regular expression by enclosing it within two forward slashes.

str = /my expression/

Matching

There are two common ways of using the regular expressions for matching:

  1. Using =~ operator
"Do you contain my expression" =~ /expression/

This returns the index of the position at which the expression is found in the string. If the expression is not found, it returns an empty string.

  1. Using match function
  if "Do you contain my expression?".match(/expression/)
  puts "Match found!"
  end

This function only checks if the string contains the expression and then returns true or false.

Example of Ruby regex

Code

Let’s look at an example of how to use regular expressions in Ruby:

# Example code for regular expressions 

  # displays index of expression 
  puts "Do you contain my expression?" =~ /expression/

  # displays nothing when the expression is not found
  puts "Do you contain my expression?" =~ /not/
  
  # using the match function 
  if "Do you contain my expression?".match(/expression/)
  puts "Match found!"
  end

  # using a modifier 'i' for case insensitivity
  if "Do you contain my expression".match(/EXPRESSION/i)
  puts "Case insensitive match found!"
  end

RELATED TAGS

ruby

CONTRIBUTOR

Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring