From 9548d5b1110c21d7f4f1ca023351e055e0e7aa03 Mon Sep 17 00:00:00 2001 From: Dylan Araps Date: Fri, 15 Jun 2018 08:26:06 +1000 Subject: [PATCH] added regex --- README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ test.sh | 6 ++++++ 2 files changed, 51 insertions(+) diff --git a/README.md b/README.md index 322572d..a0fd281 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ scripts and not full blown utilities. * [Strings](#strings) * [Trim leading and trailing white-space from string.](#trim-leading-and-trailing-white-space-from-string) * [Trim all white-space from string and truncate spaces.](#trim-all-white-space-from-string-and-truncate-spaces) + * [Use REGEX on a string.](#use-regex-on-a-string) * [Split a string on a delimiter.](#split-a-string-on-a-delimiter) * [Change a string to lowercase.](#change-a-string-to-lowercase) * [Change a string to uppercase.](#change-a-string-to-uppercase) @@ -123,6 +124,50 @@ trim_all() { } ``` +### Use REGEX on a string. + +We can use the result of `bash`'s regex matching to create a simple `sed` +replacement. + +**NOTE**: This is one of the few platform dependant `bash` features. +`bash` will use whatever regex engine is installed on the user's system. +Stick to POSIX regex features if aiming for compatibility. + +**NOTE**: This example only prints the first matching group. When using +multiple capture groups some modification will be needed. + +```sh +regex() { + # Usage: regex "string" "regex" + [[ $1 =~ $2 ]] && printf '%s\n' "${BASH_REMATCH[1]}" +} + +# Example: +# Trim leading white-space. +: regex ' hello' '^\s*(.*)' + + +# Example script usage (Validate hex colors): +_() { + colors=( + "#FFFFFF" + "#000000" + "#CDEFDC" + "#12dlks" + "red" + ) + + for color in "${colors[@]}"; do + if [[ "$color" =~ ^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$ ]]; then + printf '%s\n' "${BASH_REMATCH[1]}" + else + printf '%s\n' "error: $color is an invalid color." + fi + done +} +``` + + ### Split a string on a delimiter. ```sh diff --git a/test.sh b/test.sh index bcf4b17..3995bde 100755 --- a/test.sh +++ b/test.sh @@ -12,6 +12,11 @@ test_trim_all() { assert_equals "$result" "Hello, World" } +test_regex() { + result="$(regex " Hello, World" '^[[:space:]]*(.*)')" + assert_equals "$result" "Hello, World" +} + test_lower() { result="$(lower "HeLlO")" assert_equals "$result" "hello" @@ -130,6 +135,7 @@ main() { test_trim_string test_trim_all + test_regex test_lower test_upper test_trim_quotes