I wrote this script to find a string with only *
and !
However, it can not find any string开发者_运维百科 consists only *
I couldn't figure out what's wrong with my regular expression, Could someone please help? Thank you!
#!/bin/bash
arr=('!!' '!' '*' '*!' '**' '**!' '!*!' '***' 'bla!' )
echo star is "${arr[2]}"
for i in ${arr[@]}; do if [[ "$i" == [\!\*]* ]] ; then echo match "$i"; fi; done
You just need to quote your array in the for
statement:
for i in "${arr[@]}"; do if [[ "$i" == [*!]* ]] ; then echo match "$i"; fi; done
If you put the exclamation point second, you don't need to escape it (the asterisk doesn't need escaping in any case).
By the way, that's not a regular expression. It's a shell globbing expression.
try
for i in "${arr[@]}"; do if [[ "$i" =~ "^[\!\*]*$" ]] ; then echo match "$i"; fi; done
Edit:(for Dennis)
$ for i in "${arr[@]}"; do if [[ "$i" =~ "^[\!\*]*$" ]] ; then echo match "$i"; fi; done
match !!
match !
match *
match *!
match **
match **!
match !*!
match ***
$ for i in "${arr[@]}"; do if [[ "$i" =~ ^[\!\*]*$ ]] ; then echo match "$i"; fi; done
match !!
match !
match *
match *!
match **
match **!
match !*!
match ***
精彩评论