如何在shell中检查字符串是否包含正则表达式模式中的字符? [英] How to check if string contains characters in regex pattern in shell?

查看:27
本文介绍了如何在shell中检查字符串是否包含正则表达式模式中的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查变量是否包含(regex) other而不是0-9a-z-纯bash?

How do I check if a variable contains characters (regex) other than 0-9a-z and - in pure bash?

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

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

推荐答案

一种方法是使用 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

这篇关于如何在shell中检查字符串是否包含正则表达式模式中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆