0
0
Rubyprogramming~5 mins

Why regex is powerful in Ruby

Choose your learning style9 modes available
Introduction

Regex helps you find and work with patterns in text easily. Ruby makes using regex simple and flexible.

Checking if a user entered a valid email address.
Finding all phone numbers in a document.
Replacing certain words in a text automatically.
Splitting a sentence into words based on spaces or punctuation.
Syntax
Ruby
/pattern/flags

Patterns are written between slashes / /.

Flags like i make matching case-insensitive.

Examples
Matches the word 'cat' exactly.
Ruby
/cat/
Matches 'cat', 'Cat', 'CAT', etc. (case-insensitive).
Ruby
/cat/i
Matches one or more digits (numbers).
Ruby
/\d+/
Sample Program

This program checks if the text contains a phone number pattern like 123-456-7890. It prints a message if found.

Ruby
text = "My phone number is 123-456-7890."
if text =~ /\d{3}-\d{3}-\d{4}/
  puts "Found a phone number!"
else
  puts "No phone number found."
end
OutputSuccess
Important Notes

Ruby lets you use regex directly with strings using operators like =~ or methods like match.

Regex can be combined with Ruby's string methods for powerful text processing.

Summary

Regex finds patterns in text quickly and easily.

Ruby's regex syntax is simple and flexible.

You can use regex to check, find, replace, or split text.