0
0
Bash Scriptingscripting~10 mins

Capture groups in Bash in Bash Scripting - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to capture the first word from the string using Bash regex.

Bash Scripting
text="Hello World"
if [[ $text =~ ^([a-zA-Z]+) ]]; then
  echo "First word: ${BASH_REMATCH[[1]]}"
fi
Drag options to blanks, or click blank then click option'
A1
B0
C2
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using BASH_REMATCH[0] instead of BASH_REMATCH[1] to get the captured group.
2fill in blank
medium

Complete the code to check if the variable 'email' contains a domain using capture groups.

Bash Scripting
email="user@example.com"
if [[ $email =~ @([a-zA-Z0-9.-]+)\.com$ ]]; then
  domain=${BASH_REMATCH[[1]]}
  echo "Domain: $domain"
fi
Drag options to blanks, or click blank then click option'
A1
B0
C2
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using BASH_REMATCH[0] which returns the whole email instead of the domain.
3fill in blank
hard

Fix the error in the code to correctly capture the year from the date string.

Bash Scripting
date="2024-06-15"
if [[ $date =~ ([0-9]{4})-([0-9]{2})-([0-9]{2}) ]]; then
  year=${BASH_REMATCH[[1]]}
  echo "Year: $year"
fi
Drag options to blanks, or click blank then click option'
A0
B2
C1
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using BASH_REMATCH[0] which returns the full date string.
4fill in blank
hard

Fill both blanks to capture the username and domain from an email string.

Bash Scripting
email="alice@example.com"
if [[ $email =~ ^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.com$ ]]; then
  user=${BASH_REMATCH[[1]]}
  domain=${BASH_REMATCH[[2]]}
  echo "User: $user, Domain: $domain"
fi
Drag options to blanks, or click blank then click option'
A1
B2
C0
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 0 which returns the full email instead of parts.
5fill in blank
hard

Fill all three blanks to capture year, month, and day from a date string.

Bash Scripting
date="2024-06-15"
if [[ $date =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})$ ]]; then
  year=${BASH_REMATCH[[1]]}
  month=${BASH_REMATCH[[2]]}
  day=${BASH_REMATCH[[3]]}
  echo "Year: $year, Month: $month, Day: $day"
fi
Drag options to blanks, or click blank then click option'
A1
B2
C3
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 0 for any of the date parts.