Regular expressions (regex) in Bash scripting are used for pattern matching. They can be implemented using the =~ operator within the [[ ]] test construct. For instance, if we have a variable ‘str’ and want to check if it contains numbers, we could use:
if [[ $str =~ [0-9]+ ]]
then
echo "Contains numbers"
fi
Here, [0-9]+ is the regex that matches any sequence of digits. The + indicates one or more occurrences. If the condition is true, it echoes “Contains numbers”. Regex can also be stored in a variable:
re="[a-z]+"
if [[ $str =~ $re ]]
then
echo "Contains lowercase letters"
fi
This checks if ‘str’ has any lowercase letters.