I am trying to catch only names starting from"d" with a length 3 to 5 letters in one line:
Currently, I have this line in my script which works for each provided user name:
read -p "Enter user: " user
For example, is it possible to use a regex after the user? Example:
read -p "Enter user: " user | grep $user =~ "(d\w{3,5})"
I have read this post but does not tell me if it is possible.
CodePudding user response:
After the value of user
is set, you can examine its value.
read -p "Enter user: " user
if [[ $user =~ ^.{3,5}$ ]]; then
echo "user between 3 and 5 characters"
fi
The regular expression is not implicitly anchored to either end of the string, so you need to use ^
and $
to check that the entire string is 3-5 characters, not just that the string as a substring of 3-5 characters.
In this case, you don't even need a regular expression.
if (( 3 <= ${#user} && ${#user} <=5 )); then
...
fi
CodePudding user response:
I changed the regex to ^d[a-zA-Z]{2,4}$
which consists of:
^d
- line must START with a lowercase "d"[a-zA-Z]{2,4}
- there must be 2-4 letters after the "d" and can be in either lowercase or uppercase, numbers or symbols not permitted$
- reject any trailing characters
read -p "Enter user: " user
while ! [[ $user =~ ^d[a-zA-Z]{2,4}$ ]]; do
echo "Only names starting with "d" with a total length of 3 to 5 letters"
read -p "Enter user: " user
done