Recall & Review
beginner
What is a capture group in Bash regular expressions?
A capture group is a part of a regular expression enclosed in parentheses. It saves the matched text so you can use it later in your script.
Click to reveal answer
beginner
How do you access the text matched by a capture group in Bash?
You can access the matched text using the special array variable BASH_REMATCH. BASH_REMATCH[0] is the full match, BASH_REMATCH[1] is the first capture group, and so on.
Click to reveal answer
beginner
Example: What does this Bash code print?
[[ "hello123" =~ ([a-z]+)([0-9]+) ]]
echo "${BASH_REMATCH[1]}"
echo "${BASH_REMATCH[2]}"It prints:
hello
123
The first capture group ([a-z]+) matches 'hello', the second ([0-9]+) matches '123'.
Click to reveal answer
beginner
Why use capture groups in Bash scripts?
Capture groups let you extract parts of a string easily. For example, you can get a username from an email or a number from a filename without complicated commands.Click to reveal answer
beginner
What command structure is needed to use capture groups in Bash?
You use the double square brackets [[ ]] with the =~ operator to test a string against a regex with capture groups. Example:
[[ "$string" =~ regex ]]
Click to reveal answer
In Bash, which variable holds the text matched by capture groups after a regex test?
✗ Incorrect
BASH_REMATCH is the special array variable that stores the full match and capture groups after using [[ string =~ regex ]].
What does BASH_REMATCH[0] contain after a regex match?
✗ Incorrect
BASH_REMATCH[0] contains the entire string matched by the regex, not just a capture group.
Which operator is used inside [[ ]] to test a regex with capture groups in Bash?
✗ Incorrect
The =~ operator is used to test if a string matches a regex pattern inside [[ ]].
How do you write a capture group in a Bash regex?
✗ Incorrect
Parentheses ( ) are used to create capture groups in regular expressions.
What will happen if you try to access BASH_REMATCH before a successful regex match?
✗ Incorrect
BASH_REMATCH is only set after a successful regex match. Before that, it is empty or unset.
Explain how to use capture groups in Bash to extract parts of a string.
Think about how you test a string and then get parts of it.
You got /4 concepts.
Describe a simple real-life example where capture groups in Bash can help automate a task.
Imagine you want to get just a piece of text from a bigger string.
You got /4 concepts.