Issue
I'm writing a way to check if input is a 4 digit pin code.
I cant figure out how digit matching \d
works in bash.
^\d{4}$
is more elegant solution than ^[0-9][0-9][0-9][0-9]$
but it never matches.
Is there some way that I can use ^\d{4}$
?
Example:
#!/bin/bash -e
REGEX='^[0-9][0-9][0-9][0-9]$'
ALTREGEX='^\d{4}$'
CHECK="1234"
if [[ ! $CHECK =~ $REGEX ]]
then
echo "$REGEX didnt match"
else
echo "$REGEX matched"
fi
if [[ ! $CHECK =~ $ALTREGEX ]]
then
echo "$ALTREGEX didnt match"
else
echo "$ALTREGEX matched"
fi
I've assumed there's some issue with the variables so I've changed the variable literacy around with no success.
Solution
Bash uses basic regular expressions. \d
is part of a Perl-compatible regular expression (PCRE).
Quantifiers such as {n}
work the same in BRE.
In this case you could use ^[0-9]{4}$
Answered By - mashuptwice Answer Checked By - Terry (WPSolving Volunteer)