#!/usr/bin/env bash

# Test regular expressions.
#
# Copyright (c) 1997-2022 by Reto Kromer <https://reto.ch>
#
# This Bash script is released under a 3-Clause BSD License and is provided
# "as is" without warranty or support of any kind.


# initialise constants
SCRIPT_NAME="$(basename "${0}")"
RED='\033[1;31m'
BLUE='\033[1;34m'
NC='\033[0m'

# initialise variables
unset str
unset regex
unset tmp_str

# enable extended pattern matching features
shopt -s extglob


# process input
if (( $# != 2 )); then
  cat << EOF

Usage:
  $(basename "$0") <string> <regex>

EOF
  exit 1
else
  str="${1}"
  regex="${2}"
fi

# find and colour the matching parts
if [[ ! "${str}" =~ ${regex} ]]; then
  echo -e "regex '${RED}${regex}${NC}' does not match string '${RED}${str}${NC}'"
  exit 1
else
  tmp_str="${str}"

  while [[ "${tmp_str}" =~ (.*)(${regex})(.*) ]]; do
    tmp_str="${BASH_REMATCH[1]}${BASH_REMATCH[3]}"
    str="${BASH_REMATCH[1]}${BLUE}${BASH_REMATCH[2]}${NC}${str/${BASH_REMATCH[1]}${BASH_REMATCH[2]}/}"
  done

  echo -e "regex '${BLUE}${regex}${NC}' matches string '${str}'"
  exit 0
fi
