The Regexp class
In Ruby, the regular expression logic is encapsulated in the
There is 3 ways to instantiate a
So, the next question is: how to match this
Regexp against a
The MatchData class
Regexp class provides a
Regexp#match method that takes a
String to test as parameter
Regexp#match method returns an instance of
MatchData class encapsulates all the results of a pattern match.
I invite you to read the official documentation to learn what you can do with an instance of
For example, you can use the
MatchData#to_a to iterate through the results.
Ruby Magic Variables
Ruby provides a bunch of magic variables that are automatically assigned using the result of any new instance of
The Pattern-Matching Operator =~
In order to ease the use of regular expressions, Ruby provides the syntactic sugar
=~ . This operator matches a
Regexp against a
Note that all the magic variables are set because the
=~operator instantiate a
Regexp matches against the
The Named Captures
The named capture feature, when it’s used with the
=~ operator, has a powerful mechanism that automatically assigns the result of a matching group into a variable using the name assigned to the group into the
The named capture feature is also available with the
Regexp#match method. The main difference is that there is no variable created. In effect, the named captures are available in the returned
MatchData instance by using the
To go further
The following methods are not integrated in the core of the Ruby regex implementation. So I’ll not detail them in this post.
Anyway, you can find a link to the official documentation on each of the following methods.
Ruby adds a real value to its regexp implementation by adapting the concept to its own core features and by creating the right syntactic sugars.
May I have your attention please 🎤🎤
Feel free to subscribe here: www.rubycademy.com
Thank you for taking the time to read this post :-)
Feel free to 👏 and share this medium post if it has been useful for you.
Here is a link to my last post entitled
Ruby Case Statement Behind the scene.