【问题标题】:How to check if a string contains brackets ")("?如何检查字符串是否包含括号“)(”?
【发布时间】:2016-02-03 21:43:33
【问题描述】:

我正在尝试检查输入字符串是否包含括号,它们是:()[]{}

我写了以下代码:

#!/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:

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

【问题讨论】:

    标签: string bash shell escaping


    【解决方案1】:

    您可以使用此 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
    

    【讨论】:

    • 谢谢!我尝试将我的代码从:*['\{''}''\[''\]''('')']* 更改为 *[{}\(\)\[\]]*,但我仍然遇到同样的错误,知道为什么吗?
    • bash -x asaf.sh代替sh -x asaf.sh
    • @ItaiGanot 如果你用sh 调用你的脚本,它的行为会有所不同。改为使用bash 调用它。
    • 用引号发送参数,例如bash asaf.sh '('
    • 加上引号就可以了。有什么办法可以避免引号的要求?
    猜你喜欢
    • 2021-09-15
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多