Regular Expressions in Ruby Language

Regular Expressions in Ruby Language

Regular expressions, often referred to as “regex” or “regexp,” are powerful tools for pattern matching and text manipulation in programming. They are supported

by various programming languages, including Ruby. In Ruby, regular expressions are an essential part of string manipulation, allowing you to search, extract, and replace text based on specific patterns. In this post, we will explore the basics of regular expressions in Ruby with examples to help you understand their usage.

Creating a Regular Expression

In Ruby, you can create regular expressions using the /pattern/ syntax. For instance, let’s create a simple regular expression to match the word “Ruby” in a string:

/ruby/

This regular expression will match “ruby” anywhere in the input string, regardless of the case. To make it case-insensitive, you can use the i modifier like this:

/ruby/i

Matching Strings

You can use regular expressions to match strings within other strings using the match method:

text = "Ruby is a powerful programming language."
regex = /Ruby/
match = text.match(regex)

puts match.to_s # Output: "Ruby"

In this example, the match method returns a MatchData object, which contains information about the match. You can access the matched string using match.to_s.

Using Regular Expression Methods

Ruby provides a variety of methods for working with regular expressions. Here are some common methods:

String#scan

The scan method returns an array of all occurrences of a pattern in a string:

text = "Ruby is a Ruby language. Ruby is awesome!"
pattern = /Ruby/
matches = text.scan(pattern)

puts matches.inspect
# Output: ["Ruby", "Ruby", "Ruby"]

String#gsub

The gsub method allows you to replace text that matches a pattern with another string:

text = "I love Ruby programming. Ruby is amazing!"
pattern = /Ruby/
new_text = text.gsub(pattern, "Python")

puts new_text
# Output: "I love Python programming. Python is amazing!"

String#split

The split method divides a string into an array based on a regular expression pattern:

text = "apple,banana, cherry, date"
pattern = /,/
result = text.split(pattern)

puts result.inspect
# Output: ["apple", "banana", " cherry", " date"]

Special Characters and Escaping

Regular expressions in Ruby have special characters like . (matches any character) and * (matches zero or more occurrences). If you need to match these characters literally, you must escape them using a backslash (\):

text = "10.5 + 5 * 3"
pattern = /\+/
match = text.match(pattern)

puts match.to_s # Output: "+"

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading