function check_num {
text="$@"
# re_pattern='\d' # does not work as intended.
re_pattern='[0-9]'
if [[ "$text" =~ $re_pattern ]]; then
printf "%-30s contains a number\n" "$text"
else
printf "%-30s does not contain a number\n" "$text"
fi
}
check_num hello world
check_num The number is 42, as always
check_at_least_three() {
local text="$1"
if [[ $text =~ ... ]]; then
echo $text is at least three characters long
else
echo $text is less than three characters long
fi
}
check_at_least_three ab
check_at_least_three defg
check_at_least_three "hi jk"
${BASH_REMATCH[0]} contains the value of the text that matched the pattern.
plus
The plus sign + matches as much as possible of the preceding atom.
check_two_adjacent_x() {
local text="$1"
if [[ $text =~ (x+) ]]; then
echo In $text, I found these xs: ${BASH_REMATCH[1]}
else
echo $text does not have any xs
fi
}
check_two_adjacent_x abcdef
check_two_adjacent_x vwxyz
check_two_adjacent_x rexx
check_two_adjacent_x saxxxophone