Regular Expressions in Ruby

What Are Regular Expressions in Ruby?

Regexp is a built-in Ruby class instances of which denote regular expressions which are being used to test whether a string matches a pattern or to extract a whole or a part of a matched pattern.

There are three ways to create a regular expression: 1) /.../, 2) %r{...}, and 3) Regexp#new.


A Regexp instance method match? returns true if a given regular expression is matched and false otherwise.

/awesome/.match?('Ruby is awesome') # => true


A Regexp instance method match returns an instance of MatchData class if a pattern is matched and nil otherwise.

It is possible to capture specific parts of strings and then refer to them using an instance of MatchData.

matched_data = /(I).*(juice)\./.match('I like juice.')
# => #<MatchData "I like juice." 1:"I" 2:"juice">

matched_data[1] # => "I"
matched_data[2] # => "juice"


=~ operand returns the index of a first match if a pattern is matched or nil otherwise.

/awesome/ =~ ('Ruby is awesome') # => 8
/lame/ =~ ('Ruby is awesome') # => nil

The operand =~ is defined by both Regexp and String classes and therefore the order does not matter.

Dynamic Regular Expressions

It is possible to create dynamic regular expressions using interpolation with #{...}.

dynamic_regex = 'cat'
/#{dynamic_regex}/.match('I like cat memes.') # => #<MatchData "cat">

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.