bash 检查字符串是否包含非数字字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16875453/
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 05:34:58  来源:igfitidea点击:

Check if string contains non digit characters

bashgrep

提问by saeed hardan

How can I check if a given string contains non numeric characters, examples :

如何检查给定字符串是否包含非数字字符,示例:

x11z returns > 0
x also returns > 0
1111~ also returns > 0

By character I mean everything not between 0-9. I saw similar threads but non of them talks about "non 0-9" except they show if its a-zor A-Z.

我所说的性格是指不在 之间的一切0-9。我看到了类似的线程,但他们都没有谈论“非 0-9”,除非他们显示它是a-zA-Z

回答by tarrsalah

Just by using bashpattern matching:

只需使用bash模式匹配:

[[ "$MY_VAR" =~ ^[^0-9]+$ ]] && echo "no digit in $MY_VAR"

回答by squiguy

Just use a negated character class:

只需使用否定字符类:

grep [^0-9]

This will match any non-numeric character, and not strings composed of only digits.

这将匹配任何非数字字符,而不是仅由数字组成的字符串。

回答by Rod Klinger

Most of these suggestions return true if the first character is a digit, but don't find errors within the string. The function below returns true if the entire string is digits, false if any non-digits are detected in the string.

如果第一个字符是数字,这些建议中的大多数都会返回 true,但不会在字符串中发现错误。如果整个字符串是数字,则下面的函数返回 true,如果在字符串中检测到任何非数字,则返回 false。

function isdigit () {
   [ $# -eq 1 ] || return 1;
   [[  = *[^0-9]* ]] && return 1
   return 0
}

回答by jaypal singh

Something like this:

像这样的东西:

if [[ "xf44wd" =~ [0-9]+ ]]; then
    echo "contains $?"
    else
    echo "does no contains $?"
fi

or

或者

if [[ ! "xf44wd" =~ [0-9]+ ]]; then
    echo "does not contains $?"
    else
    echo "contains $?"
fi

回答by iruvar

Another option, a bash "containment" check

另一种选择,bash“遏制”检查

[[ "xf4fgh" = *[^0-9]* ]]
echo $?
0
[[ "1234" = *[^0-9]* ]]
echo $?
1