2015-11-03 81 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

相關問題