Reputation: 485
How can I check if a given string contains non numeric characters, examples :
x11z returns > 0
x$1 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-z
or A-Z
.
Upvotes: 7
Views: 15615
Reputation: 31
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.
function isdigit () {
[ $# -eq 1 ] || return 1;
[[ $1 = *[^0-9]* ]] && return 1
return 0
}
Upvotes: 3
Reputation: 23364
Another option, a bash "containment" check
[[ "xf4fgh" = *[^0-9]* ]]
echo $?
0
[[ "1234" = *[^0-9]* ]]
echo $?
1
Upvotes: 1
Reputation: 26415
Just by using bash
pattern matching:
[[ "$MY_VAR" =~ ^[^0-9]+$ ]] && echo "no digit in $MY_VAR"
Upvotes: 8
Reputation: 77105
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
Upvotes: 3
Reputation: 33370
Just use a negated character class:
grep [^0-9]
This will match any non-numeric character, and not strings composed of only digits.
Upvotes: 11