I am trying to match a specific command using regex based on a set of allowed commands.
This is the outcome I want to achieve:
foo --happy-cat run meow # valid command
foo --happy-cat test meow # valid command
foo --happy-cat run-away woof # invalid command
This is what I have tried to do
case $* in
(*run* | *test* | *build*) echo yes ;;
*) echo no ;;
esac
What's not working
My match falsely matches run-away
as a valid command. I only want to match run
, test
or build
surrounded by whitespace
CodePudding user response:
You will have to match spaces around given words like this:
case "$*" in
*" run "*|*" test "*|*" build "*) echo yes ;;
*) echo no ;;
esac
Also this is called glob matching not regular expressions.
Above script will match " run "
and print yes
, however for run-away
it will not match first set of globs and will print no
.
CodePudding user response:
To add to anubhava's answer, if you wanted to use actual regex you could do this:
s='foo --happy-cat run-away woof' # test string
regex='\s ((run)|(test)|(build))\s '
if [[ $s =~ $regex ]]
then
echo "yes"
else
echo "no"
fi
This has the advantage of matching whitespace that isn't just space, but also tabs.