Introduction
Capture groups let you find and save parts of text that match a pattern. This helps you work with specific pieces of text easily.
if [[ string =~ regex ]]; then echo "${BASH_REMATCH[1]}" fi
text="hello123" if [[ $text =~ ([a-z]+)([0-9]+) ]]; then echo "Letters: ${BASH_REMATCH[1]}" echo "Numbers: ${BASH_REMATCH[2]}" fi
email="user@example.com" if [[ $email =~ ([^@]+)@(.+) ]]; then echo "User: ${BASH_REMATCH[1]}" echo "Domain: ${BASH_REMATCH[2]}" fi
#!/bin/bash input="2024-06-15_report.txt" if [[ $input =~ ([0-9]{4})-([0-9]{2})-([0-9]{2})_report\.txt ]]; then year=${BASH_REMATCH[1]} month=${BASH_REMATCH[2]} day=${BASH_REMATCH[3]} echo "Year: $year" echo "Month: $month" echo "Day: $day" else echo "No match found." fi
BASH_REMATCH array hold after a successful regex match in Bash?[[ string =~ regex ]], Bash stores the full matched text in BASH_REMATCH[0].BASH_REMATCH[1] onwards.[[ string =~ regex ]] to test regex matches.string="user:1234"
if [[ $string =~ ([a-z]+):([0-9]+) ]]; then
echo "Name=${BASH_REMATCH[1]}, ID=${BASH_REMATCH[2]}"
fi
([a-z]+):([0-9]+) matches letters before colon and digits after colon in the string "user:1234".BASH_REMATCH[1] captures "user" and BASH_REMATCH[2] captures "1234".string="abc123"
if [[$string =~ ([a-z]+)([0-9]+)]]; then
echo "${BASH_REMATCH[1]} and ${BASH_REMATCH[2]}"
fi
[[ ... ]] requires spaces after [[ and before ]]. The snippet misses spaces.url="https://example.com/path/to/page"
if [[ $url =~ https://([^/]+)(/.*) ]]; then
echo "Domain: ${BASH_REMATCH[1]}"
echo "Path: ${BASH_REMATCH[2]}"
fi
https://([^/]+)(/.*) matches 'https://' literally, then captures domain (any chars except '/') and path (slash followed by anything).BASH_REMATCH[1] holds domain, BASH_REMATCH[2] holds path, correctly extracted from the URL.Pass the test and this pattern moves unknown