[Bash] Read regular expression capture groups from BASH_REMATCH

Created on November 30, 2026

Use [[ text =~ pattern ]] and BASH_REMATCH to read the full match and each capture group. The example extracts a word and number from item-123.

text='item-123'
pattern='^([a-z]+)-([0-9]+)$'

if [[ $text =~ $pattern ]]; then
    printf 'Full match: %s\n' "${BASH_REMATCH[0]}"
    printf 'Name: %s\n' "${BASH_REMATCH[1]}"
    printf 'Number: %s\n' "${BASH_REMATCH[2]}"
fi
Full match: item-123
Name: item
Number: 123

Index 0 contains the full match. Subsequent indexes contain the parenthesized groups in order. Keep the pattern variable unquoted on the right of =~ so Bash interprets it as an extended regular expression.

Extract a match within a longer string

A pattern without anchors can match part of a line.

text='status=ok id=456 elapsed=12ms'
pattern='id=([0-9]+)'

if [[ $text =~ $pattern ]]; then
    printf '%s\n' "${BASH_REMATCH[1]}"
else
    printf '%s\n' 'No match'
fi
456

Read the results after the match, since another =~ comparison updates BASH_REMATCH. Run these examples in Bash.

References

Bash