Bash Pattern matching and regular expressions Regex matching


Example

pat='[^0-9]+([0-9]+)'
s='I am a string with some digits 1024'
[[ $s =~ $pat ]] # $pat must be unquoted
echo "${BASH_REMATCH[0]}"
echo "${BASH_REMATCH[1]}"

Output:

I am a string with some digits 1024
1024

Instead of assigning the regex to a variable ($pat) we could also do:

[[ $s =~ [^0-9]+([0-9]+) ]]

Explanation

  • The [[ $s =~ $pat ]] construct performs the regex matching
  • The captured groups i.e the match results are available in an array named BASH_REMATCH
  • The 0th index in the BASH_REMATCH array is the total match
  • The i'th index in the BASH_REMATCH array is the i'th captured group, where i = 1, 2, 3 ...