Skip to content

Regex

Note: You can use the 'Copy to clipboard' icon to copy any code block to reset any file at any time.

Lab

This is the original contents of the lab file (../labs/04-regex/04-regex.lab.sh).

Follow the instructions in the file to solve the lab.

# Assume "LAB04_STRING" is passed as the "$1" positional parameter
# Set a string below that match the regex in "LAB04_REGEX"
LAB04_STRING="YourStringHere"
export LAB04_STRING

# Assume "LAB04_REGEX" is passed as the "$2" positional parameter
LAB04_REGEX="^[0-4a-h]+"
export LAB04_REGEX

sobash_assert_string_matches_regex() {

  local -n string
  local -n regex

  string="$1"
  regex="$2"

  if [[ "${string}" =~ ${regex} ]]; then
    echo -e "\n[INFO] ${FUNCNAME[0]} | String (${string}) had a regex match (${BASH_REMATCH[0]})."
    return 0
  else
    echo -e "\n[FAIL] ${FUNCNAME[0]} | String (${string}) did NOT have a regex match (${BASH_REMATCH[0]})." 1>&2
    return 2
  fi

}

Test

This is the original contents of the test file (../labs/04-regex/04-regex.test.sh).

Review the test cases and your lab file.

Will the lab file (../labs/04-regex/04-regex.lab.sh) pass all test cases?

#!/usr/bin/env bash

test_assert_string_matches_regex() {

   ../build/sobash assert-string-matches-regex LAB04_STRING LAB04_REGEX
   assertEquals 0 $?

}
source ./shunit2

When ready, run the following to execute the tests above against the lab file:

cd "${HOME}/bash-programming/src/" \ 
  && ./test.sh lab 04-regex

Solution

This is the original contents of the solution file (../labs/04-regex/04-regex.solution.sh).

This file contains an example of a viable solution that passes all the test cases.

# Assume "LAB04_STRING" is passed as the "$1" positional parameter
# Set a string below that match the regex in "LAB04_REGEX"
LAB04_STRING="4a259"
export LAB04_STRING

# Assume "LAB04_REGEX" is passed as the "$2" positional parameter
LAB04_REGEX="^[0-4a-h]+"
export LAB04_REGEX

sobash_assert_string_matches_regex() {

  local -n string
  local -n regex

  string="$1"
  regex="$2"

  if [[ "${string}" =~ ${regex} ]]; then
    echo -e "\n[INFO] ${FUNCNAME[0]} | String (${string}) had a regex match (${BASH_REMATCH[0]})."
    return 0
  else
    echo -e "\n[FAIL] ${FUNCNAME[0]} | String (${string}) did NOT have a regex match (${BASH_REMATCH[0]})." 1>&2
    return 2
  fi

}

Run the following to execute the tests above against the solution file:

cd "${HOME}/bash-programming/src/" \ 
  && ./test.sh solution 04-regex

Feel free to run the following to override the contents of the lab file with the solution file.

cd "${HOME}/bash-programming/labs/" \ 
  && cp ./04-regex/04-regex.{solution,lab}.sh