Regex Literals
Pattern basics.
What Is a Regular Expression?
A regular expression (regex) is a pattern used to match text. In Ruby, regex is a first-class object of class Regexp.
You use regex to search, validate, and extract parts of strings.
- Match a word, digit, or symbol
- Validate emails, phone numbers
- Extract pieces from messy text
pattern = /hello/
puts pattern.class
puts(pattern.match?('hello world'))Regex Literals with Slashes
The most common way to write a regex in Ruby is between two forward slashes: /pattern/.
This is called a regex literal. Everything between the slashes is the pattern.
ruby = /ruby/
puts ruby.class
puts(ruby.match?('I love ruby'))
puts(ruby.match?('I love python'))