Regexp Implementation in Ruby

How Ruby takes advantage of the language to naturally implementing regular expressions into its core.

Tech - RubyCademy
RubyCademy
Published in
2 min readMar 4, 2018

--

The Regexp class

In Ruby, the regular expression logic is encapsulated in the Regexp class.

There is 3 ways to instantiate a Regexp

So, the next question is: how to match this Regexp against a String ?

The MatchData class

The Regexp class provides a Regexp#match method that takes aString to test as a parameter

The Regexp#match method returns an instance of MatchData.

The 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 MatchData .

For example, you can use 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 MatchData

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 String

Note that all the magic variables are set because the =~operator instantiate a MatchDataif the Regexp matches against the String .

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 in the Regexp instance

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 MatchData#[] method

To go further

The following methods are not integrated into 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.

Conclusion

Ruby adds real value to its regexp implementation by adapting the concept to its own core features and by creating the right syntactic sugars.

Ruby Mastery

We’re currently finalizing our first online course: Ruby Mastery.

Join the list for an exclusive release alert! 🔔

🔗 Ruby Mastery by RubyCademy

Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.

💚

--

--