Regular Expressions
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
.
Match?
A Regexp instance method match?
returns true
if a given regular expression is matched and false
otherwise.
/awesome/.match?('Ruby is awesome') # => true
Match
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">