0
0
Rubyprogramming~5 mins

Common patterns and character classes in Ruby

Choose your learning style9 modes available
Introduction

We use common patterns and character classes to find or check specific types of characters in text easily.

Checking if a password has letters and numbers.
Finding all digits in a phone number.
Extracting words from a sentence.
Validating if an email address has the right characters.
Syntax
Ruby
/[pattern]/

Patterns go inside slashes / / in Ruby.

Character classes like \d or \w match groups of characters.

Examples
Matches any single digit (0-9).
Ruby
/\d/
Matches one or more word characters (letters, digits, or underscore).
Ruby
/\w+/
Matches any single vowel letter.
Ruby
/[aeiou]/
Matches any character that is NOT a digit.
Ruby
/[^0-9]/
Sample Program

This program looks inside the text "Hello123" to find digits and words using common patterns.

Ruby
text = "Hello123"

puts "Digits found:"
text.scan(/\d/).each { |d| puts d }

puts "Words found:"
text.scan(/\w+/).each { |w| puts w }
OutputSuccess
Important Notes

Use double backslashes \\ in Ruby strings to write special patterns like \d.

Character classes help you avoid writing many separate characters.

Square brackets [] define a set of characters to match.

Summary

Common patterns help find specific characters in text.

Character classes like \d and \w match digits and words.

Use these patterns inside slashes / / in Ruby.