0

I am working on a homework assignment to validate whether an entered string is in all lowercase letters. Here is the basic script that we are provided.

Here is the line I need to change.

if [[ "$input" =~ Add your regular expression here ]]

If I put [a-z] entering anything with just one instance of a lowercase letter will validate. With [[:lower:]] "Brian" will validate and "cats" will not but gibberish such as trhrh is fine. I don't know the regex to use here. I would greatly appreciate any help.

2 Answers 2

2

Test whether the string contains anything that is not a lower case letter.

if [[ "$input" =~ [^[:lower:]] ]]; then
    # contains something that is not a lower case letter
else
    # contain only lower case letters
fi

or,

if ! [[ "$input" =~ [^[:lower:]] ]]; then
    # contain only lower case letters
fi

The ^ at the start of a bracketed expression inverses the sense of the match, so that [^abc] matches any single character that is not a, b, or c.

Alternatively, match the whole length of the string by anchoring the string at both ends:

if [[ "$input" =~ ^[[:lower:]]+$ ]]; then
    # contain only lower case letters
fi

The ^ at the start of the expression only anchors to the start of the string while the $ at the end anchors to the end of the string. In between these we allow only lower case letter using [[:lower:]]+, i.e. one or more lower case letters. Using * in place of + would allow the expression to successfully match on an empty string too.

Note also the difference between [[:lower:]] (matches a single lower case letter) and [:lower:] matches one of the characters :, l, o, w, e, or r). In the original question, you said that Brian was matched by [:lower:] while cats wasn't, which should make sense now. In an edit, you changed the expression to the correct [[:lower:]], and cats should now also be matched.


With a globbing match in place for the regular expression match:

if [[ "$input" == *[![:lower:]]* ]]; then
    # contains something that is not a lower case letter
else
    # contain only lower case letters
fi

In a globbing pattern, ! at the start of a bracketed expression works the same as the ^ in the regular expression case (although I believe bash also recognizes ^ there in globbing patterns).

0

You can also check with this one Liner if you want :

echo "$input" | grep -qE '^[[:lower:]]*$' && echo "All LowerCase" || echo "Not All LowerCase"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .