Challenge - 5 Problems
Bash Capture Groups Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
What is the output of this Bash script using capture groups?
Consider the following Bash script that uses a regex with capture groups. What will it print?
Bash Scripting
text="User: alice, ID: 42" if [[ $text =~ User: ([a-z]+), ID: ([0-9]+) ]]; then echo "Name=${BASH_REMATCH[1]}, Number=${BASH_REMATCH[2]}" else echo "No match" fi
Attempts:
2 left
💡 Hint
Remember that BASH_REMATCH stores the full match at index 0, and capture groups start at index 1.
✗ Incorrect
The regex matches the text, capturing 'alice' and '42' in groups 1 and 2. BASH_REMATCH[1] and BASH_REMATCH[2] hold these values.
📝 Syntax
intermediate1:30remaining
Which Bash regex syntax correctly captures two groups?
Which option correctly uses capture groups in a Bash regex inside [[ ]]?
Attempts:
2 left
💡 Hint
Bash regex inside [[ ]] does not use slashes or escaped parentheses.
✗ Incorrect
In Bash, regex is written without slashes and parentheses are used directly for capture groups.
🔧 Debug
advanced2:30remaining
Why does this Bash script fail to capture groups?
Given this script, why does it print 'No match' even though the text looks correct?
text="abc123"
if [[ $text =~ abc([0-9]+) ]]; then
echo "Number: ${BASH_REMATCH[1]}"
else
echo "No match"
fi
Attempts:
2 left
💡 Hint
Check which shell runs the script; sh does not support BASH_REMATCH.
✗ Incorrect
BASH_REMATCH is a Bash feature. Running the script with sh causes the regex match and capture groups to fail.
🚀 Application
advanced3:00remaining
Extract domain and path from URL using Bash capture groups
You want to extract the domain and path from this URL using Bash regex capture groups:
url="https://example.com/path/to/page"
Which option correctly extracts domain and path into variables domain and path?
Attempts:
2 left
💡 Hint
The domain ends before the first slash after https://, and path starts after the slash.
✗ Incorrect
Option A correctly captures the domain as all characters except slash, then the path as the rest after the slash.
🧠 Conceptual
expert3:00remaining
How many capture groups are in this Bash regex?
In the Bash regex used inside [[ ]]:
regex='(a(b)c)(d(e)f)'
How many capture groups does this regex have, and what does BASH_REMATCH[3] contain if matched against 'abcdef'?
Attempts:
2 left
💡 Hint
Count all parentheses pairs, including nested ones.
✗ Incorrect
There are 4 capture groups, numbered by opening parenthesis order: group 1 '(a(b)c)' matches 'abc', group 2 '(b)' matches 'b', group 3 '(d(e)f)' matches 'def', group 4 '(e)' matches 'e'. Therefore, BASH_REMATCH[3] contains 'def'.