0
0
Rubyprogramming~5 mins

Regex literal syntax (/pattern/) in Ruby

Choose your learning style9 modes available
Introduction

Regex literals let you write patterns to find or match text easily.

Checking if a word exists in a sentence.
Validating simple input like phone numbers or emails.
Splitting text by a pattern.
Replacing parts of text that match a pattern.
Syntax
Ruby
/pattern/

The pattern goes between two slashes /.

You can add options after the second slash to change behavior (like case-insensitive).

Examples
Matches 'cat' anywhere in the text.
Ruby
/cat/
Matches 'dog' ignoring uppercase or lowercase letters.
Ruby
/dog/i
Matches one or more digits (numbers).
Ruby
/\d+/
Sample Program

This program checks if the word 'cat' is in the text, ignoring case. It prints a message based on the result.

Ruby
text = "I have a Cat and a dog."

if text =~ /cat/i
  puts "Found cat!"
else
  puts "No cat found."
end
OutputSuccess
Important Notes

Use \ to escape special characters inside the pattern.

The =~ operator returns the position of the match or nil if no match.

Summary

Regex literals are written between slashes /pattern/.

They help find or check text patterns quickly.

You can add options like i for case-insensitive matching.