Search notes:

bash - regular expressions

function check_num {
  text="$@"
# re_pattern='\d'     # does not work as intended.
  re_pattern='[0-9]'


  if [[ "$text" =~ $re_pattern ]]; then
      printf "%-30s contains a number\n" "$text"
  else
      printf "%-30s does not contain a number\n" "$text"
  fi
}

check_num hello world
check_num The number is 42, as always
Github repository about-Bash, path: /variables/regular-expressions/check-num

dot

The dot matches any character, including spaces.
check_at_least_three() {
  local text="$1"

  if [[ $text =~ ... ]]; then
    echo $text is at least three characters long
  else
    echo $text is less than three characters long
  fi
}

check_at_least_three ab
check_at_least_three defg
check_at_least_three "hi jk"
Github repository about-Bash, path: /variables/regular-expressions/dot

BASH_REMATCH

The ${BASH_REMATCH[*]} array can be used to query the values within parentheses after a match:
pattern='([0-9]+)[^[:digit:]]+([0-9]+)'
text='foo 12345 bar 42 baz'

if [[ $text =~ $pattern ]]; then
  echo 1st number: ${BASH_REMATCH[1]}
  echo 2nd number: ${BASH_REMATCH[2]}
fi
Github repository about-Bash, path: /variables/regular-expressions/BASH_REMATCH
${BASH_REMATCH[0]} contains the value of the text that matched the pattern.

plus

The plus sign + matches as much as possible of the preceding atom.
check_two_adjacent_x() {
  local text="$1"

  if [[ $text =~ (x+) ]]; then
    echo In $text, I found these xs: ${BASH_REMATCH[1]}
  else
    echo $text does not have any xs
  fi
}

check_two_adjacent_x abcdef
check_two_adjacent_x vwxyz
check_two_adjacent_x rexx
check_two_adjacent_x saxxxophone
Github repository about-Bash, path: /variables/regular-expressions/plus

See also

variables
regular expressions
sed, grep

Index