bash 如何在shell中检查字符串是否包含正则表达式模式中的字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19850529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:32:41  来源:igfitidea点击:

How to check if string contains characters in regex pattern in shell?

regexstringbash

提问by Justin

How do I check if a variable contains characters (regex)otherthan 0-9a-zand -in pure bash?

如何检查,如果一个变量包含的字符(正则表达式)其他0-9a-z-纯bash的?

I need a conditional check. If the string contains characters other than the accepted characters above simply exit 1.

我需要有条件的检查。如果字符串包含上述接受字符以外的字符,则简单地exit 1.

回答by higuaro

One way of doing it is using the grepcommand, like this:

一种方法是使用grep命令,如下所示:

 grep -qv "[^0-9a-z-]" <<< $STRING

Then you ask for the grepreturned value with the following:

然后您grep使用以下内容请求返回值:

if [ ! $? -eq 0 ]; then
    echo "Wrong string"
    exit 1
fi

As @mpapis pointed out, you can simplify the above expression it to:

正如@mpapis 指出的,您可以将上面的表达式简化为:

grep -qv "[^0-9a-z-]" <<< $STRING || exit 1

Also you can use the bash =~operator, like this:

您也可以使用 bash=~运算符,如下所示:

if [[ ! "$STRING" =~ [^0-9a-z-] ]] ; then  
    echo "Valid"; 
else 
    echo "Not valid"; 
fi

回答by mpapis

casehas support for matching:

case支持匹配:

case "$string" in
  (+(-[[:alnum:]-])) true ;;
  (*) exit 1 ;;
esac

the format is not pure regexp, but it works faster then separate process with grep- which is important if you would have multiple checks.

该格式不是纯正则表达式,但它的工作速度比单独的进程更快grep- 如果您要进行多次检查,这一点很重要。

回答by NerdMachine

Using Bash's substitution engine to test if $foo contains $bar

使用 Bash 的替换引擎测试 $foo 是否包含 $bar

bar='[^0-9a-z-]'
if [ -n "$foo" -a -z "${foo/*$bar*}" ] ; then
  echo exit 1
fi