Introduction
Regex literals let you write patterns to find or match text easily.
Regex literals let you write patterns to find or match text easily.
/pattern/
The pattern goes between two slashes /.
You can add options after the second slash to change behavior (like case-insensitive).
/cat/
/dog/i
/\d+/
This program checks if the word 'cat' is in the text, ignoring case. It prints a message based on the result.
text = "I have a Cat and a dog." if text =~ /cat/i puts "Found cat!" else puts "No cat found." end
Use \ to escape special characters inside the pattern.
The =~ operator returns the position of the match or nil if no match.
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.
cat?/pattern/./cat/.Dog case-insensitively in Ruby?i option after the slashes makes matching case-insensitive./Dog/i uses the correct i flag for case-insensitive matching.text = "Hello World" match = text =~ /world/i puts match
=~ returns the index of the first match or nil if no match./world/i matches 'World' ignoring case. In "Hello World", 'World' starts at index 6 (0-based).pattern = /hello/i/
/hello/i is invalid and causes a syntax error.a or A in a string using a regex literal. Which regex literal correctly matches this requirement?i simplifies matching both./\b[a]\w*/i which matches word boundary, then 'a' (case-insensitive), then zero or more word chars. This matches words starting with 'a' or 'A'.Pass the test and this pattern moves unknown