0
0
Rubyprogramming~15 mins

Capture groups in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Extracting Names with Capture Groups in Ruby
📖 Scenario: You work at a company that receives customer messages. Each message contains a greeting with the customer's first and last name. You want to extract these names to greet them personally.
🎯 Goal: Build a Ruby program that uses capture groups in a regular expression to extract first and last names from a greeting string.
📋 What You'll Learn
Create a string variable called message with a greeting containing a first and last name.
Create a regular expression variable called name_regex that uses capture groups to find the first and last name.
Use the match method on message with name_regex to get the match data.
Print the extracted first and last names separately.
💡 Why This Matters
🌍 Real World
Extracting names from customer messages helps personalize communication in customer support and marketing.
💼 Career
Understanding capture groups and regex matching is useful for data extraction, text processing, and automation tasks in software development.
Progress0 / 4 steps
1
Create the greeting message
Create a string variable called message and set it to the exact value "Hello, my name is John Doe."
Ruby
Need a hint?

Use double quotes and assign the exact greeting text to message.

2
Create the regular expression with capture groups
Create a regular expression variable called name_regex that matches the pattern "Hello, my name is FirstName LastName." and uses capture groups to capture the first and last names as words.
Ruby
Need a hint?

Use parentheses () to create capture groups for first and last names. Use \w+ to match word characters.

3
Match the regular expression to extract names
Use the match method on message with name_regex and assign the result to a variable called match_data.
Ruby
Need a hint?

Call match on message with name_regex and save the result.

4
Print the extracted first and last names
Print the first name by accessing match_data[1] and the last name by accessing match_data[2], each on its own line.
Ruby
Need a hint?

Use puts to print each captured group from match_data.