Ruby RegExp

christian.dinh's avatar
Published Jul 30, 2021Updated Sep 9, 2021
Contribute to Docs

In Ruby, Regular Expressions (shortened as RegExp), are used to describe and match patterns in strings. This functionality is housed in the Regexp class.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours

Syntax

Regular expressions can be created in three ways:

# With / /
regexp1 = /code/
# With %r{ }
regexp2 = %r{code}
# With Regexp.new()
regexp3 = Regexp.new("code")

Finding Patterns in Strings

To see if a given string matches a regular expression, use .match().

puts regexp1.match("codecademy") # Output: code

To test if there even was a match (true or false), use .match?():

puts regexp1.match?("codecademy") # Output: true

All contributors

Contribute to Docs

Learn Ruby on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours