Regular Expressions

Let's learn how we can use regular expressions in Ruby.

Some people, when confronted with a problem, think, “I know, I’ll use regular expressions.” Now they have two problems.

That’s a pretty famous joke, and it refers to the fact that regular expressions can be difficult to solve.

However, once we know some basics about them, they’re also extremely powerful, and we can do amazing things with them, not only in Ruby but also, for example, in our editor and command-line tools.

Regular expressions are sort of a swiss army knife for finding things in strings (text), extracting parts of them, or mass replacing certain bits with something else.

For example, we could do any of these tasks:

  • Extract area codes from phone numbers.

  • Validate the format of an email address.

  • For a list of files ,a-01.mpeg, b-02.mpeg, and c-03.mpeg, change their names to 01-a.mpeg, 02-b.mpeg, and 03-c.mpeg.

Remember: Regular expressions are a language to describe patterns of text. Wikipedia calls them “a sequence of characters that define a search pattern.”

For example, the pattern [0-9]+! means that there needs to be at least one digit, and it needs to be followed by an exclamation mark. Does the pattern ([\w]+)-([\d]+)\.mpeg look intimidating and cryptic? It does, and that’s why regular expressions have a kind of strange reputation in programming. They’re super powerful, but they’re also kind of a pain.

A little bit of history

The main reason regular expressions are so hard to read is that they date as far back as 1956, and their first implementations in programming came in the late 1960s. Back then, every single character of code was worth a lot. Memory was extremely limited, and code had to be as terse as possible.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy