Solution to matching brackets in Bash

This commit is contained in:
2023-07-15 17:36:40 +02:00
parent 09bf8bc515
commit 9dea7a1fcc
7 changed files with 958 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
#!/usr/bin/env bash
input="$1"
# Remove all characters except brackets, braces, and parentheses
cleaned_input=$(echo "$input" | tr -cd '[]{}()')
# Keep replacing any valid pair of brackets, braces, or parentheses with an empty string
while [[ $cleaned_input =~ (\(\)|\{\}|\[\]) ]]; do
cleaned_input=${cleaned_input//\(\)/}
cleaned_input=${cleaned_input//\{\}/}
cleaned_input=${cleaned_input//\[\]/}
done
# If the cleaned string is empty, all pairs are matched and nested correctly
if [[ -z $cleaned_input ]]; then
echo "true"
else
echo "false"
fi