Ruby - Match a Pattern in a String

1. Introduction

Pattern matching is a fundamental operation in text processing and Ruby offers robust support for it through its Regular Expression (Regexp) class. In this blog post, we'll explore how to utilize Ruby's Regexp class to search for patterns in a string.

A regular expression, often abbreviated as regex or regexp, is a sequence of characters that specifies a search pattern. This pattern can be used for tasks such as searching, extracting, or even replacing substrings in a string. Ruby's Regexp class provides methods to perform these operations on strings.

2. Program Steps

1. Define the string in which you want to search.

2. Define the pattern you want to search for using or the shorthand //.

3. Use the match method to search for the pattern in the string.

4. Print the result.

3. Code Program

# Step 1: Define the string
text = "Ruby is an elegant programming language."
# Step 2: Define the pattern
pattern = /elegant/
# Step 3: Search for the pattern in the string
result = text.match(pattern)
# Step 4: Print the result
if result
  puts "Matched: '#{result[0]}'"
  puts "No match found."


Matched: 'elegant'


1. text: This is the string where we are searching for our pattern.

2. pattern = /elegant/: Here, we define the pattern we're searching for. The forward slashes (//) are a shorthand way to create a new Regexp object in Ruby.

3. result = text.match(pattern): The match method is used to search for the pattern in the string. If the pattern is found, it returns a MatchData object; otherwise, it returns nil.

4. if result ... else ... end: This conditional checks if a match was found. If a match was found, we print the matched word; otherwise, we print "No match found."

Using regular expressions, we can define more complex patterns to match various criteria in a string, making Regexp a powerful tool for string processing in Ruby.