2015-11-03 60 views
3

我想检查是否有输入字符串包含括号,它们是:?()[]{}如何检查是否字符串包含括号“()”

我写了下面的代码:

#!/bin/bash 
str="$1" 
if [ -z "$str" ]; then 
    echo "Usage: $(basename $0) string" 
    exit 1 
fi 
if [[ "$str" == *['\{''}''\[''\]''('')']* ]]; 
then 
    echo "True" 
else 
    echo "False" 
fi 

如果字符串中包含的部分包括:[]{}则输出是正确的,但如果字符串包含()然后我得到一个错误:

-bash: syntax error near unexpected token `(' 

这些都是事我已经尝试到目前为止:

*['\(''\)']* 
*['()']* 
*[()]* 

任何想法应该如何写?

编辑#1:

[[email protected] ~]# date 
Tue Nov 3 18:39:37 IST 2015 
[[email protected] ~]# bash -x asaf.sh { 
+ str='{' 
+ '[' -z '{' ']' 
+ [[ { == *[{}\[\]\(\)]* ]] 
+ echo True 
True 
[[email protected] ~]# bash -x asaf.sh (
-bash: syntax error near unexpected token `(' 
[[email protected] ~]# 

回答

4

您可以使用此glob图案()[]逃脱内[...]

[[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no" 

测试:

str='abc[def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no" 
yes 

str='abc}def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no" 
yes 

str='abc[def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no" 
yes 

str='abc(def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no" 
yes 

str='abc)def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no" 
yes 

str='abc{}def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no" 
yes 

str='abc}def' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no" 
yes 

str='abcdef' && [[ $str == *[{}\(\)\[\]]* ]] && echo "yes" || echo "no" 
no 
+0

谢谢!我已经尝试将我的代码改为:'* ['\''''''''[''''] *'to'* [{} \(\)\ [\] ] *'但我仍然得到同样的错误,有什么想法为什么? –

+0

[It works here](http://ideone.com/on11F6)你确定你在使用BASH吗? – anubhava

+0

而不是'sh -x asaf.sh'使用'bash -x asaf.sh' – anubhava

相关问题