Skip to Content
Course content

24: Regular Expressions in Ruby

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of a Regular Expression (RegEx) as a "wanted poster" for text. If you were looking for one specific person, you'd just use their name. But if you're looking for anyone who fits a certain profile—say, someone wearing a red hat, carrying a briefcase, and roughly six feet tall—you describe the pattern. You don't care who the individual is, as long as they match those specific traits.

In Ruby, RegEx does exactly that for your strings. Instead of looking for the exact word "Error", you can look for "any line that starts with a date, followed by the word 'Error', and ends with a number." We aren't searching for a static piece of text; we're searching for a shape.

The Anatomy of a Ruby Pattern

In Ruby, we wrap our patterns in forward slashes: /pattern/. This tells Ruby, "Hey, this isn't a string; it's a Regular Expression object."

Let's look at a real-world scenario. Imagine you're processing a list of product IDs that always look like this: two uppercase letters, a hyphen, and four digits (e.g., TS-1234). Here is how I'd build that "wanted poster":

product_id_pattern = /[A-Z]{2}-\d{4}/

Let's break that down point-by-point:

  • [A-Z]: This is a character class. It means "any single uppercase letter from A to Z".
  • {2}: This is a quantifier. It says "exactly two of the thing that came right before this".
  • -: This is just a literal hyphen. It must be exactly a hyphen.
  • \d: This is a shorthand for "any digit (0-9)".
  • {4}: Again, a quantifier. "Exactly four digits".

Hunting for Matches

Once you have your pattern, you need to actually use it against a string. I usually lean on two different ways depending on what I need. If I just need a "yes or no" answer, I use the =~ operator.

sku = "TS-1234"
if sku =~ /[A-Z]{2}-\d{4}/
  puts "Valid SKU!"
end

The =~ operator returns the index of the first match, or nil if nothing is found. Since nil is "falsy" in Ruby, it works perfectly in an if statement. It's quick, it's clean, and it's what I use 90% of the time for simple validation.

However, if you actually need to extract the data, use the .match method. This returns a MatchData object, which is basically a little treasure chest containing everything the RegEx found.

Capturing the Good Stuff

This is where RegEx gets powerful. By using parentheses (), you can create "capture groups." This is like telling Ruby, "Match the whole pattern, but I specifically want you to remember this one part of it for me."

Let's say you're parsing a log entry: "USER_ID: 502 - Login successful". You want the ID number, but not the rest of the noise.

log_line = "USER_ID: 502 - Login successful"
match_data = log_line.match(/USER_ID: (\d+) -/)

if match_data
  user_id = match_data[1] # This grabs the first capture group
  puts "Processing user #{user_id}..."
end

I've spent way too many hours of my career staring at complex RegEx strings that looked like a cat walked across a keyboard. My advice? Start small. Build your pattern piece by piece and test it against a few strings before you try to write one massive, "perfect" expression. It'll save you a massive headache.

Replacing Chaos with Order

Finally, there's .gsub (global substitution). This is your go-to tool for cleaning up messy data. You can use RegEx to find patterns and replace them with something else.

Imagine you have a string with inconsistent spacing and you want to normalize it to a single space. Instead of a dozen .strip or .split calls, you can just do this:

messy_text = "Too    many    spaces      here"
clean_text = messy_text.gsub(/\s+/, " ") 
# \s means any whitespace, + means "one or more"
puts clean_text # "Too many spaces here"



📋 Practical Task

The Server Log Parser

You've been handed a raw log file from a legacy server. Each line follows this format: [YYYY-MM-DD] LEVEL: Message. For example: [2023-10-12] ERROR: Database connection failed.

Your task is to write a Ruby script that processes an array of these log strings. For every line that has a level of "ERROR" or "CRITICAL", you must extract the date and the message and print them in the following format: "Alert: On [date], a critical issue occurred: [message]".

Starter Data:

logs = [
  "[2023-11-01] INFO: System boot complete",
  "[2023-11-01] ERROR: Disk space low",
  "[2023-11-02] DEBUG: Heartbeat sent",
  "[2023-11-02] CRITICAL: Kernel panic",
  "[2023-11-03] INFO: User logged in"
]

Requirements:

  • Use a Regular Expression with capture groups to isolate the date and the message.
  • Ensure you only target "ERROR" or "CRITICAL" levels (Hint: use the | "OR" operator in your RegEx).
  • Ignore "INFO" and "DEBUG" lines entirely.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.