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


Regular expressions can be created in three ways:

# With / /
regexp1 = /code/
# With %r{ }
regexp2 = %r{code}
# With
regexp3 ="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


Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Ruby on Codecademy