...

/

Regular Expressions

Regular Expressions

This lesson summarizes the use of regular expressions in Ruby in detail.

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 quite a pain to figure out.

However, once you know some basics about them, they’re also extremely powerful, and you can do amazing things with them, not only in Ruby, but also, for example, in your 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.

E.g. you could do:

  • Extract area codes from phone numbers.
  • Validate the format of an email address.
  • For a list of files a-01.mpeg, b-02.mpeg, c-03.mpeg, change their names to 01-a.mpeg, 02-b.mpeg, 03-c.mpeg.

Regular expressions are a language to describe patterns of text. Wikipedia says: a sequence of characters that define a search pattern.

For example the pattern [0-9]+! means: There needs to be at least one digit, and it needs to be followed by an exclamation mark. The pattern ([\w]+)-([\d]+)\.mpeg

Does this stuff look scary and cryptic? You bet. That’s why regular expressions have kind of a strange reputation in programming. They’re super powerful, but they’re also kind of a pain: Like black magic, this power comes at a price.

A little bit of history…

The main reason why the language that is defined as regular expressions is so hard to read is that it dates back as far ...

Create a free account to access the full course.

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