Regular Expressions

Examples of use

if [[ "${string}" =~ ${REGEX} ]]; then
  echo 'matches'
else
  echo "doesn't match"
fi
# 0 = matches
# 1 = doesn't match
[[ "${string}" =~ ${REGEX} ]]; echo $?
# colour matched substrings
# see also: Built-in Shell Variables (and Arrays)

RED='\033[1;31m'
NC='\033[0m'

tmp_string="${string}"

while [[ "${tmp_string}" =~ (.*)(${REGEX})(.*) ]]; do
  tmp_string="${BASH_REMATCH[1]}${BASH_REMATCH[3]}"
  string="${BASH_REMATCH[1]}${RED}${BASH_REMATCH[2]}${NC}${string/${BASH_REMATCH[1]}${BASH_REMATCH[2]}/}"
done

echo -e "${string}"

Examples of regex

ISO 8601 date and time format

# any time in the HH:MM:SS format
REGEX="([01][0-9]|2[0-3])(:[0-5][0-9]){2}"

# any time either in the HH:MM:SS or HH:MM format
REGEX="([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?"
# the current date in the YYYY-mm-dd format
REGEX="$(date +'%Y-%m-%d')"
REGEX="$(date +'%F')"

# "valid" date of the current year in the YYYY-mm-dd format
REGEX="$(date +'%Y')-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"

# "valid" date between 1970-01-01 and 2023-12-31
REGEX="(19[7-9][0-9]|20[01][0-9]|202[0-3])-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"

Container for ProRes 422 and 4444 encoded video

REGEX='^(mov|mkv|mxf)$'

LTO cartridge barcode

# the correct one is
REGEX="^[A-Z0-9]{6}(L[5-9]|M8)$"

# but some implementations are less strict
REGEX="^[A-Z0-9]{6}(L[5-9]|M8)?$"

Version of a BagIt File Packaging Format

REGEX="^1.0|0.9[3-7]$"

2023-08-15