且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-21 10:45:59

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

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

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

然后您要求 grep 返回的值如下:

Then you ask for the grep returned value with the following:

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

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

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

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

你也可以使用 bash =~ 操作符,像这样:

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

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